package com.h3c.nem.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.eos.common.util.Result;
import com.eos.common.util.UserUtils;
import com.h3c.nem.async.AsyncSendMessage;
import com.h3c.nem.client.EosSyncDataClient;
import com.h3c.nem.client.PsaClient;
import com.h3c.nem.client.SapClient;
import com.h3c.nem.dto.*;
import com.h3c.nem.dto.client.NewHrssWorkerClientDTO;
import com.h3c.nem.dto.client.NewWorkerClientDTO;
import com.h3c.nem.dto.client.SdAllWorkerClientDTO;
import com.h3c.nem.dto.client.WorkerInfoClientDTO;
import com.h3c.nem.dto.enums.TodoTaskNodeEnum;
import com.h3c.nem.dto.form.Attachment;
import com.h3c.nem.dto.form.GetFormBusinessData;
import com.h3c.nem.dto.form.HistoryInfo;
import com.h3c.nem.dto.mapstruct.TbFlowInstDTOMapper;
import com.h3c.nem.dto.mapstruct.TbWorkerDTOMapper;
import com.h3c.nem.dto.mapstruct.TbWorkerMap;
import com.h3c.nem.entity.*;
import com.h3c.nem.enums.EducationLevelEnum;
import com.h3c.nem.mapper.*;
import com.h3c.nem.service.*;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.CommonUtil;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbWorkerServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_worker serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbWorkerServiceImpl extends ServiceImpl<TbWorkerMapper, TbWorker> implements ITbWorkerService {

    @Value("${busi.adminids}")
    private String adminDomainAccounts;
    @Resource
    private TbWorkerMapper tbWorkerMapper;
    @Resource
    private TbFlowInstMapper tbFlowInstMapper;
    @Resource
    private TbWorkerPromiseMapper tbWorkerPromiseMapper;
    @Resource
    private TbApprovalRecordMapper tbApprovalRecordMapper;
    @Resource
    private TbNewerTaskMapper tbNewerTaskMapper;
    @Autowired
    private ITbNewerTaskService tbNewerTaskService;
    @Autowired
    private ITbFlowInstService tbFlowInstService;

    @Autowired
    private TbFlowInstServiceImpl tbFlowInstServiceImpl;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Resource
    private ITbPreWorkerService preWorkerService;
    @Resource
    private ISdDeptService sdDeptService;
    @Resource
    private TbOfferStudyMapper tbOfferStudyMapper;
    @Autowired
    private SdEmailTemplateMapper sdEmailTemplateMapper;
    @Autowired
    private CommService commService;
    @Resource
    private ISdDeptService deptService;
    @Autowired
    SdAllWorkerMapper sdAllWorkerMapper;
    @Resource
    private EosSyncDataClient eosSyncDataClient;
    @Resource
    private ISdAllWorkerService allWorkerService;
    @Resource
    private ITbTeacherService teacherService;
    @Resource
    private PsaClient psaClient;
    @Resource
    private ISdTodoTaskService todoTaskService;
    @Resource
    private ISdEmailTemplateService emailTemplateService;
    @Resource
    private AsyncSendMessage asyncSendMessage;

    @Resource
    private ITbOfferWorkerService offerWorkerService;

    @Resource
    private TbTeachScheduleMapper teachScheduleMapper;
    @Resource
    SdDeptMapper sdDeptMapper;

    @Autowired(required = false)
    private UserUtils userUtils;
    @Value("${performance.manage.account}")
    private String performanceAccount;

    @Value("${performance.manage.password}")
    private String performancePassword;
    @Value("${inventory.account}")
    private String inventoryAccount;

    @Value("${inventory.password}")
    private String inventoryPassword;
    @Value("${begin-check-new-worker-date}")
    private String startJoinTime;
    @Value("${overdueDay}")
    private Integer overdueDay;
    @Value("${todotask.pc.url}")
    String todoPcUrl;
    @Value("${eos.nem.password}")
    String eosNemPassword;
    @Value("${eos.nem.account}")
    String eosNemAccount;
    private static final String systemId = "HR_NEM";
    @Value("${postgres.username}")
    private String postgresUsername;
    @Value("${postgres.password}")
    private String postgresPassword;
    @Resource
    private SapClient sapClient;
    @Value("${hrss.nem.account}")
    private String hrssUId;
    @Value("${hrss.nem.password}")
    private String hrssPasswd;
    @Value("${postgres.db.url}")
    private String postgresUrl;
    int planProbationMonth = 3;
    @Value("${block.bp.id}")
    private String blockBp;
    @Value("${nem.in.error.mail}")
    private String inErrorMail;

    @Value("${block.dept.id}")
    private String blockDept;

    @Value("${notSyncSecManagerDeptIds}")
    private String notUpdateDept;

    @Value("${noIttpRdDeptIds}")
    private String noIttpRdDeptIds;

    /**
     * @param dto
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<TbWorkerDTO> selectFuzzyByDto(TbWorkerSeaDTO dto) {
        //List<TbWorker> list = tbWorkerMapper.selectByExample(initFuzzyExample(dto));
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MONTH, -1);
        Date lastMonth = instance.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
        dto.setScoreMonth(sf.format(lastMonth));
        List<TbWorkerDTO> list = tbWorkerMapper.queryListByFuzzy(dto);
        list.forEach(item -> {
            //11 填写月度工作承诺；12 月度承诺审核；13 月度考核评价；21 填写转正计划；22 转正计划审核;23 转正考核评价；31 执行小任务；32 审核小任务；99 已完成；
            Integer flowStage = item.getFlowStage();
            if (flowStage != null) {
                switch (flowStage) {
                    case 11:
                        item.setFlowStageName("填写月度工作承诺");
                        break;
                    case 12:
                        item.setFlowStageName("月度承诺审核");
                        break;
                    case 13:
                        item.setFlowStageName("月度考核评价");
                        break;
                    case 21:
                        item.setFlowStageName("填写转正计划");
                        break;
                    case 22:
                        item.setFlowStageName("转正计划审核");
                        break;
                    case 23:
                        item.setFlowStageName("转正考核评价");
                        break;
                    case 31:
                        item.setFlowStageName("执行小任务");
                        break;
                    case 32:
                        item.setFlowStageName("审核小任务");
                        break;
                    case 99:
                        item.setFlowStageName("已完成");
                        break;
                    case 100:
                        item.setFlowStageName("终止");
                        break;
                }
            }

            //拼接直属部门
            StringBuilder codeChainName = new StringBuilder(item.getDept1name());
            if (!StringUtils.isEmpty(item.getDept2name())) {
                codeChainName.append("\\").append(item.getDept2name());
            }
            if (!StringUtils.isEmpty(item.getDept3name())) {
                codeChainName.append("\\").append(item.getDept3name());
            }
            if (!StringUtils.isEmpty(item.getDept4name())) {
                codeChainName.append("\\").append(item.getDept4name());
            }
            item.setCodeChainName(codeChainName.toString());
            if (commService.getAllWorkerDoFromLocalCache(item.getWorkerId()) == null) {
                item.setQuit(true);
            } else {
                item.setQuit(false);
            }

            String workerGrade = item.getWorkerGrade();
            if (!StringUtils.isEmpty(workerGrade)) {
                int i = 0;
                String[] gradeArr = workerGrade.split(",");
                StringBuilder workerGradeAfter = new StringBuilder();
                for (String grade : gradeArr) {
                    i++;
                    String gradeAfter = grade.split(":")[0] + "（第" + i + "月）：" + grade.split(":")[1];
                    workerGradeAfter.append(gradeAfter).append(",");
                }
                item.setWorkerGrade(workerGradeAfter.substring(0, workerGradeAfter.length() - 1));
            }

        });
        return list;
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<TbWorkerDTO> selectByDto(TbWorkerDTO dto) {
        //List<TbWorker> list = tbWorkerMapper.selectByExample(initExample(dto));
        List<TbWorker> list = tbWorkerMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), TbWorker.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), TbWorkerDTO.class);
    }

    /**
     * @Title: getBasicInfo
     * @Description: 新员工页面基本信息
     * @Params: [com.h3c.nem.dto.TbWorkerDTO]
     * @Return: com.h3c.nem.dto.TbWorkerDTO
     * @Author: f23104
     * @Time: 2022/1/25 16:42
     */
    @Override
    public TbWorkerDTO getBasicInfo(TbWorkerDTO dto) {
        //传入的新员工工号
        String workerId = dto.getWorkerId();
        TbWorker tbWorker = tbWorkerMapper.selectById(workerId);
        if (tbWorker != null) {
            //新员工基础数据
            TbWorkerDTO tbWorkerDTO = TbWorkerDTOMapper.INSTANCE.workerToWorkerDTO(tbWorker);
            String teacher = tbWorkerDTO.getTeacherInfo();
            String directManager = tbWorkerDTO.getDirectManager();
            String secondManager = tbWorkerDTO.getSecondManager();
            String deptContactor = tbWorkerDTO.getDeptContactor();
            SdDept dept = commService.getDept(tbWorkerDTO.getDirectDeptId());
            String bpUserId = dept.getBpUserId();
            if (!StringUtils.isEmpty(bpUserId)) {
                String firstBp = bpUserId.split(",")[0];
                String[] bpIds = bpUserId.split(",");
                for (String bpId : bpIds) {
                    if (bpIds.length > 1 && !blockBp.contains(bpId)) {
                        firstBp = bpId;
                        break;
                    }
                }
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(firstBp);
                if (workerDO != null) {
                    tbWorkerDTO.setDeptBp(workerDO.getWorkerName() + "/" + firstBp);
                    tbWorkerDTO.setDeptBpId(firstBp);
                    tbWorkerDTO.setDeptBpEmail(workerDO.getEmail());
                }
            }
            if (!StringUtils.isEmpty(teacher)) {
                teacher = teacher.split(",")[0];
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(teacher.split("/")[1]);
                if (workerDO != null) {
                    tbWorkerDTO.setTeacherEmail(workerDO.getEmail());
                    tbWorkerDTO.setTeacherId(workerDO.getWorkerId());
                }
            }
            if (!StringUtils.isEmpty(directManager)) {
                directManager = directManager.split(",")[0];
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(directManager.split("/")[1]);
                if (workerDO != null) {
                    tbWorkerDTO.setDirectManagerEmail(workerDO.getEmail());
                    tbWorkerDTO.setDirectManagerId(workerDO.getWorkerId());
                }
            }
            if (!StringUtils.isEmpty(secondManager)) {
                secondManager = secondManager.split(",")[0];
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(secondManager.split("/")[1]);
                if (workerDO != null) {
                    tbWorkerDTO.setSecondManagerEmail(workerDO.getEmail());
                    tbWorkerDTO.setSecondManagerId(workerDO.getWorkerId());
                }
            }
            if (!StringUtils.isEmpty(deptContactor)) {
                deptContactor = deptContactor.split(",")[0];
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(deptContactor.split("/")[1]);
                if (workerDO != null) {
                    tbWorkerDTO.setDeptContactorEmail(workerDO.getEmail());
                    tbWorkerDTO.setDeptContactorId(workerDO.getWorkerId());
                }
            }
            QueryWrapper<TbFlowInst> instWrapper = new QueryWrapper<>();
            instWrapper.eq("worker_id", workerId)
                    .eq("flow_code", BusiEnumDefine.FLOW_TASK)
                    .ne("flow_status", BusiEnumDefine.flowStatusTermination);
            //新员工小任务
            List<TbFlowInst> workerTaskList = tbFlowInstMapper.selectList(instWrapper);
            List<TbNewerTask> tbNewerTasks = tbNewerTaskMapper.queryList(new TbNewerTask());
            Map<String, String> taskNameMap = new HashMap<>();
            tbNewerTasks.forEach(task -> taskNameMap.put(task.getTaskId(), task.getTaskName()));
            List<TbFlowInstDTO> instDTOList = new ArrayList<>();
            workerTaskList.forEach(task -> {
                TbFlowInstDTO taskDTO = TbFlowInstDTOMapper.INSTANCE.instToInstDTO(task);
                taskDTO.setTaskName(taskNameMap.get(taskDTO.getFlowNote()));
                instDTOList.add(taskDTO);
            });
            tbWorkerDTO.setNewerTaskList(instDTOList);
            return tbWorkerDTO;
        } else {
            throw new AppBusinessException("未查到当前新员工信息");
        }
    }

    @Override
    @Transactional
    public void startFirstMonthAssessment(List<String> workerIds) {
        String loginUserId = commService.getLoginUserId();
        List<TbWorker> dbList = list(new QueryWrapper<TbWorker>().in("worker_id", workerIds));
        List<TbFlowInst> addFlowList = new LinkedList<>();
        List<SdNoticeRecord> toTeacherList = new LinkedList<>();
        List<SdTodoTask> tasks = new LinkedList<>();
//        List<TbTeachSchedule> teacherScheduleTaskList = new LinkedList<>();
//        List<SdAllWorker> allWorkerList = allWorkerService.list();
        SdEmailTemplate toTeacherTemplate = emailTemplateService.getById("TO_TEACHER");
//        Map<String, SdAllWorker> allWorkerMap = new HashMap<>();
//        allWorkerList.forEach(i -> allWorkerMap.put(i.getWorkerId(), i));
        Date now = new Date();
        dbList.forEach(item -> {
            if (item.getWorkerStatus() > 1) {
                throw new AppBusinessException("工号为" + item.getWorkerId() + "的员工试用期考核流程已经启动");
            }
            if (StringUtils.isEmpty(item.getTeacherInfo())) {
                throw new AppBusinessException("工号为" + item.getWorkerId() + "的员工没有指定思想导师");
            }
            if (StringUtils.isEmpty(item.getFinalApprover())) {
                throw new AppBusinessException("工号为" + item.getWorkerId() + "的员工没有指定最终考核人");
            }
            if (StringUtils.isEmpty(item.getFinalJudger())) {
                throw new AppBusinessException("工号为" + item.getWorkerId() + "的员工没有指定最终评价人");
            }

            //first month start
            TbFlowInst tempFlowInst = new TbFlowInst();
            tempFlowInst.setWorkerId(item.getWorkerId());
            tempFlowInst.setWorkerName(item.getWorkerName());
            tempFlowInst.setWorkerDeptId(item.getDirectDeptId());
            tempFlowInst.setFlowCode(BusiEnumDefine.FLOW_MONTH_FILL);
            tempFlowInst.setFlowName(BusiEnumDefine.FLOW_MONTH_FILL_NAME);
            tempFlowInst.setFlowId(IdWorker.nextId() + "");
            tempFlowInst.setFlowStatus(BusiEnumDefine.FLOW_STATUS_MONTH_FILL_PLAN);
            tempFlowInst.setCurrentStage("填写月度工作承诺");
            tempFlowInst.setCreateTime(now);
            tempFlowInst.setArriveTime(now);
            tempFlowInst.setApprovalUserIds(item.getWorkerId());
            String teacherId = item.getTeacherInfo().split("/")[1];
            SdAllWorker teacher = commService.getAllWorkerDoFromLocalCache(teacherId);
            //发送邮件

            String workerNameInfo = item.getWorkerName() + "/" + item.getWorkerId();
            String emailTemplateTitle = toTeacherTemplate.getEmailTemplateTitle();
            String emailTemplateContent = toTeacherTemplate.getEmailTemplateContent();
            emailTemplateTitle = emailTemplateTitle.replace("{员工姓名}", workerNameInfo);
            emailTemplateContent = emailTemplateContent.replace("{员工姓名}", workerNameInfo);

            SdNoticeRecord toTeacherRecord = new SdNoticeRecord();
            toTeacherRecord.setNoticeId(IdWorker.nextId() + "");
            toTeacherRecord.setFlowId(IdWorker.nextId() + "");
            toTeacherRecord.setApplyUserId(loginUserId);
            toTeacherRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            toTeacherRecord.setTargetId(teacher.getWorkerId());
            toTeacherRecord.setTargetName(teacher.getWorkerName());
            toTeacherRecord.setTargetEmail(teacher.getEmail());
            toTeacherRecord.setNoticeTitle(emailTemplateTitle);
            toTeacherRecord.setNoticeContent(emailTemplateContent);
            toTeacherRecord.setCreateTime(new Date());
            toTeacherRecord.setCopyToEmail("");

            TbTeachSchedule teachSchedule = new TbTeachSchedule();
            teachSchedule.setWorkerId(item.getWorkerId());
            teachSchedule.setTeacherId(teacherId);
            teachSchedule.setStartDate(item.getJoinDate());
            teachScheduleMapper.insert(teachSchedule);
            toTeacherList.add(toTeacherRecord);
            addFlowList.add(tempFlowInst);
        });
        List<String> acc = new LinkedList<>();
        workerIds.forEach(i -> {
            SdAllWorker allWorker = commService.getAllWorkerDoFromLocalCache(i);
            if (allWorker != null) {
                acc.add(allWorker.getDomainAccount());
            }
        });

        //关闭刚入职时发送给bp的待办
        List<SdTodoTask> closeTaskList = todoTaskService.list(new QueryWrapper<SdTodoTask>()
                .in("adduserid", acc).eq("processid",BusiEnumDefine.FLOW_NEW_WORKER_NOTICE));
        closeTaskList.forEach(i -> {
            i.setEnduserid(i.getEnduserid() + commService.getLoginUserDTO().getAccount());
            i.setAuthorid("");
            i.setAuthorname("");
            i.setNodeid("FINISHED");
            i.setNodename("已完成");
            i.setStatus("APPROVED");
            todoTaskService.sendTodoTask(i);
            todoTaskService.update(new UpdateWrapper<SdTodoTask>().lambda()
                    .set(SdTodoTask::getAuthorid,"")
                    .set(SdTodoTask::getAuthorname,"")
                    .set(SdTodoTask::getNodeid,i.getNodeid())
                    .set(SdTodoTask::getNodename,i.getNodename())
                    .set(SdTodoTask::getStatus,i.getStatus())
                    .set(SdTodoTask::getEnduserid,i.getEnduserid())
                    .eq(SdTodoTask::getAdduserid,i.getAdduserid())
                    .eq(SdTodoTask::getProcessid,i.getProcessid()));
        });
        SdEmailTemplate startTemplate = emailTemplateService.getById("WORKER_START");
        TodoTaskNodeEnum orderStatusEnum = TodoTaskNodeEnum.getEnumByValue(BusiEnumDefine.FLOW_STATUS_MONTH_FILL_PLAN);
        tbFlowInstService.saveBatch(addFlowList);
        update(new UpdateWrapper<TbWorker>()
                .in("worker_id", workerIds)
                .set("flow_stage", 11)
                .set("worker_status", BusiEnumDefine.WORKER_STATUS_CONDUCT));

        //开启小任务
        Map<String, String> map = tbNewerTaskService.postTaskByWorkerId(dbList, null);
        //start flow
        addFlowList.forEach(item -> {
            SdAllWorker allWorker = commService.getAllWorkerDoFromLocalCache(item.getWorkerId());
            //发送邮件
            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId(item.getFlowId());
            sdNoticeRecord.setApplyUserId(loginUserId);
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            sdNoticeRecord.setTargetId(allWorker.getWorkerId());
            sdNoticeRecord.setTargetName(allWorker.getWorkerName());
            sdNoticeRecord.setTargetEmail(allWorker.getEmail());
            sdNoticeRecord.setNoticeTitle(startTemplate.getEmailTemplateTitle());
            sdNoticeRecord.setNoticeContent(startTemplate.getEmailTemplateContent());
            sdNoticeRecord.setCreateTime(new Date());
            sdNoticeRecord.setCopyToEmail("");
            toTeacherList.add(sdNoticeRecord);
            //发送待办
            SdTodoTask task = createTask(item.getFlowId(), allWorker.getWorkerId(), item.getApprovalUserIds(), item.getFlowCode()
                    , orderStatusEnum.getName(), orderStatusEnum.toString(), BusiEnumDefine.FLOW_MONTH_FILL_NAME);
            tasks.add(task);
        });
        log.info("发送邮件");
        asyncSendMessage.sendMessage(toTeacherList);
        asyncSendMessage.sendTodoTask(tasks);
    }

    @Override
    public File exportWorkerList(TbWorkerSeaDTO paramsDTO) {
        List<TbWorkerDTO> tbWorkerDTOS = selectFuzzyByDto(paramsDTO);
        Map<Integer, String> workerStatusMap = new HashMap<>();
        workerStatusMap.put(BusiEnumDefine.WORKER_STATUS_WAIT, "待启动考核");
        workerStatusMap.put(BusiEnumDefine.WORKER_STATUS_CONDUCT, "考核进行中");
        workerStatusMap.put(BusiEnumDefine.WORKER_STATUS_CORRECTED, "已转正");
        workerStatusMap.put(BusiEnumDefine.WORKER_STATUS_ELIMINATED, "已淘汰");
        workerStatusMap.put(BusiEnumDefine.WORKER_STATUS_TERMINATED, "已终止");
        tbWorkerDTOS.forEach(item -> {
            item.setWorkerName(item.getWorkerName() + "/" + item.getWorkerId());
            item.setWorkerStatusName(workerStatusMap.get(item.getWorkerStatus()));
        });
        return commService.generateExportFile("新入职员工列表", BusiEnumDefine.NEW_WORKER_EXPORT, (List) tbWorkerDTOS);
    }

    @Override
    public Map<String, Object> homePageChart() {
        Date nowTemp = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(nowTemp);
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);
        Date now = instance.getTime();
        int nowYear = instance.get(Calendar.YEAR);
        instance.add(Calendar.DAY_OF_MONTH, 14);
        Date twoWeekAfter = instance.getTime();
        instance.add(Calendar.DAY_OF_MONTH, -14);
        instance.add(Calendar.DAY_OF_MONTH, -overdueDay);
        Date overdueDate = instance.getTime();
        instance.add(Calendar.DAY_OF_MONTH, overdueDay);
        instance.set(Calendar.DAY_OF_MONTH, instance.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date thisMonthFistDate = instance.getTime();
        int thisMonth = instance.get(Calendar.MONTH) + 1;
        instance.add(Calendar.MONTH, 2);
        instance.set(Calendar.DAY_OF_MONTH, instance.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date threeMonthEndDate = instance.getTime();
        Set<Integer> deptChildIds = null;
        int[] months = new int[3];
        months[0] = thisMonth;
        months[1] = (thisMonth + 12) % 12 + 1;
        months[2] = (thisMonth + 13) % 12 + 1;
        boolean adminAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN);
        boolean gbbzAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_GBBZ);
        boolean bpAuth = commService.checkLoginUserBP();
        boolean conAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR);
        boolean manAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_MANAGER);
        String loginUserId = commService.getLoginUserId();
        Map<String, Object> resultMap = initChartMap(months);
        if (adminAuth) {
            deptChildIds = null;
        }else if (bpAuth || manAuth || gbbzAuth || conAuth) {
            deptChildIds = deptService.getAuthDeptIds(bpAuth, false, manAuth, gbbzAuth);
            if (deptChildIds.isEmpty() && !conAuth) {
                return resultMap;
            }
        } else {
            return resultMap;
        }
        boolean isMore18;
        if (adminAuth || gbbzAuth) {
            isMore18 = true;
        } else {
            isMore18 = false;
        }
        //当前待入职员工合计
        int waitJoinCount = offerWorkerService.count(new QueryWrapper<TbOfferWorker>()
                .ge("plan_report_date", now)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds));
        //当前未转正员工
        int waitPassCount = tbWorkerMapper.waitPassCount(deptChildIds, isMore18, conAuth ? loginUserId : null);
        //当前带启动考核员工
        int waitStartCount = tbWorkerMapper.waitStartCount(deptChildIds, isMore18, conAuth ? loginUserId : null);

        //今年累计入职新员工
        int yearJoinCount = tbWorkerMapper.yearJoinCount(nowYear, deptChildIds, isMore18, conAuth ? loginUserId : null);

        //今年累计转正新员工
        int yearPassCount = tbWorkerMapper.yearPassCount(nowYear, now, deptChildIds, isMore18, conAuth ? loginUserId : null);
        //认证导师人数
        int teacherCount = teacherService.count(new QueryWrapper<TbTeacher>()
                .eq("certified_status", 3)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds));
        //在途待办
        Integer onWayFlowCountTm = tbFlowInstMapper.selectCount(new QueryWrapper<TbFlowInst>()
                .ne("flow_status", BusiEnumDefine.FLOW_STATUS_FINISH)
                .ne("flow_status",BusiEnumDefine.flowStatusTermination)
                .in(deptChildIds != null, "worker_dept_id", deptChildIds));
        //超期待办
        Integer overdueFlowCountTm = tbFlowInstMapper.selectCount(new QueryWrapper<TbFlowInst>()
                .ne("flow_status", BusiEnumDefine.FLOW_STATUS_FINISH)
                .ne("flow_status",BusiEnumDefine.flowStatusTermination)
                .in(deptChildIds != null, "worker_dept_id", deptChildIds)
                .lt("create_time", overdueDate));
        int onWayFlowCount = onWayFlowCountTm == null ? 0 : onWayFlowCountTm;
        int overdueFlowCount = overdueFlowCountTm == null ? 0 : overdueFlowCountTm;

        //近两周待入职转正人员
        //待转正员工合计
        List<Map<String, Object>> _2WePassedWorkerTotals = tbWorkerMapper.get2WePassedWorkerTotals(now, twoWeekAfter, deptChildIds, isMore18, conAuth ? loginUserId : null);
               /* listMaps(new QueryWrapper<TbWorker>()
                .select("COUNT(1) count","DAY(pass_date) day")
                .ge("pass_date", now)
                .le("pass_date", twoWeekAfter)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds)
                .groupBy("day"));*/
        //待入职员工合计
        List<Map<String, Object>> _2WeJoinedWorkerTotals = offerWorkerService.listMaps(new QueryWrapper<TbOfferWorker>()
                .select("COUNT(1) count", "DAY(join_date) day")
                .ge("join_date", now)
                .le("join_date", twoWeekAfter)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds)
                .groupBy("day"));

        //近三个月待入职转正人员
        //待转正员工合计
        List<Map<String, Object>> _3MonPassedWorkerTotals = tbWorkerMapper.get3MonPassedWorkerTotals(thisMonthFistDate,
                threeMonthEndDate, deptChildIds, isMore18, conAuth ? loginUserId : null);
/*                listMaps(new QueryWrapper<TbWorker>()
                .select("COUNT(1) count","MONTH(pass_date) month")
                .ge("pass_date", thisMonthFistDate)
                .le("pass_date", threeMonthEndDate)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds)
                .groupBy("month")
                .orderByAsc("month"));*/
        //待入职员工合计
        List<Map<String, Object>> _3MonJoinedWorkerTotals = offerWorkerService.listMaps(new QueryWrapper<TbOfferWorker>()
                .select("COUNT(1) count", "MONTH(plan_report_date) month")
                .ge("plan_report_date", thisMonthFistDate)
                .le("plan_report_date", threeMonthEndDate)
                .in(deptChildIds != null, "direct_dept_id", deptChildIds)
                .groupBy("month")
                .orderByAsc("month"));

        resultMap.put("waitJoinCount", waitJoinCount);
        resultMap.put("waitPassCount", waitPassCount);
        resultMap.put("waitStartCount", waitStartCount);
        resultMap.put("yearJoinCount", yearJoinCount);
        resultMap.put("yearPassCount", yearPassCount);
        resultMap.put("teacherCount", teacherCount);
        resultMap.put("onWayFlowCount", onWayFlowCount);
        resultMap.put("overdueFlowCount", overdueFlowCount);
        resultMap.put("_2WePassedWorkerTotals", _2WePassedWorkerTotals);
        resultMap.put("_2WeJoinedWorkerTotals", _2WeJoinedWorkerTotals);
        resultMap.put("_3MonPassedWorkerTotals", completionData(_3MonPassedWorkerTotals, months));
        resultMap.put("_3MonJoinedWorkerTotals", completionData(_3MonJoinedWorkerTotals, months));
        resultMap.put("_3Months", months);
        return resultMap;
    }

    private Map<String, Object> initChartMap(int[] months) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("waitJoinCount", 0);
        resultMap.put("waitPassCount", 0);
        resultMap.put("yearJoinCount", 0);
        resultMap.put("yearPassCount", 0);
        resultMap.put("teacherCount", 0);
        resultMap.put("onWayFlowCount", 0);
        resultMap.put("waitStartCount", 0);
        resultMap.put("overdueFlowCount", 0);
        resultMap.put("_2WePassedWorkerTotals", 0);
        resultMap.put("_2WeJoinedWorkerTotals", 0);
        resultMap.put("_3MonPassedWorkerTotals", completionData(new LinkedList<>(), months));
        resultMap.put("_3MonJoinedWorkerTotals", completionData(new LinkedList<>(), months));
        resultMap.put("_3Months", months);
        return resultMap;
    }

    private List<Object> completionData(List<Map<String, Object>> list, int[] months) {
        List<Object> resList = new LinkedList<>();
        if (list == null) {
            for (int i = 0; i < 3; i++) {
                resList.add(0);
            }
            return resList;
        }
        int size = list.size();
        if (size == 3) {
            for (Map<String, Object> map : list) {
                resList.add(map.get("count"));
            }
            return resList;
        }
        int i = 0;
        for (int k = 0; k < months.length; k++) {
            if (i < size && (int) list.get(i).get("month") == months[k]) {
                resList.add(list.get(i).get("count"));
                i++;
            } else {
                resList.add(0);
            }
        }
        return resList;
    }

    public TbInstNodeDTO getWorkerFlowNodes(TbWorkerDTO dto) {
        String loginUserId = commService.getLoginUserIdWithNoException();
        String workerId = dto.getWorkerId();
        if (StringUtils.isEmpty(workerId)) {
            throw new AppBusinessException("员工工号为空");
        }
        TbWorker tbWorker = tbWorkerMapper.selectById(workerId);
        //入职日期
        Date joinDate = tbWorker.getJoinDate();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        TbInstNodeDTO instNodeDTO = new TbInstNodeDTO();
        //总共几个节点即试用期月数
        instNodeDTO.setTotalNode(tbWorker.getProbationMonth());
        instNodeDTO.setStartDate(sdf.format(joinDate));
        List<TbFlowInst> tbFlowInsts = tbFlowInstMapper.queryFlowInstInOrder(workerId);
        //按顺序放好的填写流程
        Map<Integer, TbFlowInst> fillInstMap = new HashMap<>();
        //按顺序放好的评价流程
        Map<Integer, TbFlowInst> examInstMap = new HashMap<>();
        int fillCount = 1;
        int examCount = 1;
        for (TbFlowInst inst : tbFlowInsts) {
            String flowCode = inst.getFlowCode();
            if (flowCode.equals(BusiEnumDefine.FLOW_MONTH_FILL) || flowCode.equals(BusiEnumDefine.FLOW_TRANSFER_FILL)) {
                if (fillInstMap.get(1) == null) {
                    fillInstMap.put(1, inst);
                } else {
                    fillInstMap.put(++fillCount, inst);
                }
            }
            if (flowCode.equals(BusiEnumDefine.FLOW_MONTH_APPRAISAL) || flowCode.equals(BusiEnumDefine.FLOW_TRANSFER_APPRAISAL)) {
                if (examInstMap.get(1) == null) {
                    examInstMap.put(1, inst);
                } else {
                    examInstMap.put(++examCount, inst);
                }
            }
        }
        instNodeDTO.setCurrentNode(fillCount);
        List<TbNodeDTO> nodeList = new ArrayList<>();
        for (int i = 1; i <= tbWorker.getProbationMonth(); i++) {
            TbNodeDTO nodeDTO = new TbNodeDTO();
            TbFlowInst fillInst = fillInstMap.get(i);
            TbFlowInst examInst = examInstMap.get(i);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(joinDate);
            calendar1.add(Calendar.MONTH, i - 1);
            Date time1 = calendar1.getTime();
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(joinDate);
            calendar2.add(Calendar.MONTH, i);
            Date time2 = calendar2.getTime();
            nodeDTO.setFlowPeriod(sdf.format(time1) + "至" + sdf.format(time2));
            nodeDTO.setEndDate(sdf.format(time2));
            nodeDTO.setExamResult("暂无");
            if (fillInst != null) {
                nodeDTO.setFillFlowId(fillInst.getFlowId());
                nodeDTO.setNodeStateFill(getStatusName(fillInst.getFlowStatus()));
                nodeDTO.setNodeApprovalUserFill(getWorkerInfo(fillInst.getApprovalUserIds()));
            }
            if (examInst != null) {
                nodeDTO.setExamFlowId(examInst.getFlowId());
                nodeDTO.setNodeStateExam(getStatusName(examInst.getFlowStatus()));
                nodeDTO.setNodeApprovalUserExam(getWorkerInfo(examInst.getApprovalUserIds()));
                if (examInst.getFlowStatus().equals(BusiEnumDefine.flowStatusFinished)) {
                    TbApprovalRecord approvalRecord = tbApprovalRecordMapper.queryApprovalInOrder(examInst.getFlowId());
                    if (approvalRecord != null) {
                        if (examInst.getFlowCode().equals(BusiEnumDefine.FLOW_MONTH_APPRAISAL)) {
                            nodeDTO.setExamResult(approvalRecord.getApprovalScore());
                            if (!StringUtil.isEmpty(loginUserId) && workerId.equals(loginUserId)) {
                                nodeDTO.setExamResult("通过");
                            }
                        } else {
                            nodeDTO.setExamResult(approvalRecord.getApprovalResult().equals(BusiEnumDefine.APPROVAL_APPROVE) ? "通过" : "不通过");
                            if("应届毕业生".equals(tbWorker.getDataSrc())){
                                nodeDTO.setExamResult(approvalRecord.getApprovalScore()+" "+(approvalRecord.getApprovalResult().equals(BusiEnumDefine.APPROVAL_APPROVE) ? "通过" : "不通过"));
                            }
                        }
                    }
                }
            }
            nodeList.add(nodeDTO);
        }
        instNodeDTO.setNodeList(nodeList);
        return instNodeDTO;
    }

    public String getWorkerInfo(String workerId) {
        if (!StringUtils.isEmpty(workerId)) {
            SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(workerId);
            if (workerDO != null) {
                return workerDO.getWorkerName() + "/" + workerId;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public String getStatusName(Integer flowStatus) {
        if (flowStatus != null) {
            switch (flowStatus) {
                case 11:
                    return "填写月度承诺";
                case 12:
                    return "月度承诺审核";
                case 13:
                    return "月度考核评价";
                case 21:
                    return "填写转正计划";
                case 22:
                    return "转正计划审核";
                case 23:
                    return "转正考核评价";
                case 99:
                    return "已完成";
                default:
                    return null;
            }
        } else {
            return null;
        }
    }

    @Override
    @Transactional
    public void syncAllWorker() {
        try {
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            String token = userUtils.getToken(eosNemAccount, eosNemPassword);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("entryDate", "1801-1-1");
            Result<List<SdAllWorkerClientDTO>> result = null;
            for (int i = 0; i < 3; i++) {
                log.info("====获取第{}次视图====",i);
                String workerData = eosSyncDataClient.syncNewWorker("Bearer " + token,jsonObject.toJSONString());
                result = JSON.parseObject(workerData, new TypeReference<Result<List<SdAllWorkerClientDTO>>>() {
                });
                if (result.getCode() == 20216) {
                    break;
                }
            }
            if (result.getCode() == 20217) {
                log.error(result.toString());
                XxlJobLogger.log(result.toString());
                throw new AppBusinessException(result.getMessage());
            }
            List<SdAllWorkerClientDTO> workerClientList = result.getData();
            Set<String> newAllWorkerIdSet = workerClientList.stream().map(SdAllWorkerClientDTO::getWorkerId).collect(Collectors.toSet());
            List<SdAllWorker> quitWorkerList = new ArrayList<>();
            List<SdAllWorker> saveWorkerList = new ArrayList<>();
            Map<String, Object> dataCacheMap = CommService.dataCacheMap;
            Set<String> dataCacheKeySet = dataCacheMap.keySet();
            dataCacheKeySet.forEach(key -> {
                if (key.contains("allworker-") && !newAllWorkerIdSet.contains(key.split("-")[1])) {
                    //找到离职员工并删除
                    SdAllWorker allWorker = (SdAllWorker) dataCacheMap.get(key);
                    if (allWorker != null && (allWorker.getWorkerType() == null || allWorker.getWorkerType() == 1) && allWorker.getJobType() != null) {
                        quitWorkerList.add(allWorker);
                        dataCacheMap.remove(key);
                    }
                }
            });
            Pattern pattern = Pattern.compile("[^0-9]");
            for (SdAllWorkerClientDTO allWorker : workerClientList) {
                SdAllWorker worker = new SdAllWorker();
                BeanUtils.copyProperties(allWorker,worker);
                if (worker.getJobTypeLevel() != null) {
                    worker.setJobLevel(pattern.matcher(worker.getJobTypeLevel()).replaceAll(""));
                }
                worker.setWorkerName(worker.getWorkerName().replace(","," "));
                worker.setSyncTime(now);
                worker.setWorkerType(1);
                worker.setCertificateNoTopSix(worker.getCertificateNoTopSix() == null? "" :worker.getCertificateNoTopSix().substring(0,6));
                dataCacheMap.put("allworker-" + worker.getWorkerId(), worker);
                saveWorkerList.add(worker);
            }
            log.info("===离职员工::{}",quitWorkerList);
            sendEmaiForUserResign(quitWorkerList);
            sendEmailForNewUserResign(quitWorkerList);
            //删除离职导师
            deleteResignTeacher(quitWorkerList);
            allWorkerService.remove(new QueryWrapper<SdAllWorker>().eq("worker_type", 1));//只删除正式员工
            allWorkerService.saveBatch(saveWorkerList);
            Date yes = DateUtil.yesterday().toJdkDate();
            for (SdAllWorker allWorker : saveWorkerList) {
                TbTeachSchedule tbTeachSchedule = new TbTeachSchedule();
                tbTeachSchedule.setEndDate(yes);
                teachScheduleMapper.update(tbTeachSchedule, new UpdateWrapper<TbTeachSchedule>().lambda()
                        .eq(TbTeachSchedule::getWorkerId, allWorker.getWorkerId()).isNull(TbTeachSchedule::getEndDate));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error::",e);
            XxlJobLogger.log(e);
            throw new AppBusinessException("同步所有员工失败");
        }
    }

    public void updateWorkerInfo(){
        String token = "Bearer " + userUtils.getToken(eosNemAccount, eosNemPassword);
//        String invToken = "Bearer " + userUtils.getToken(inventoryAccount, inventoryAccount);
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyyMM");
        String startDate = yyyy_MM.format(now);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("entryDate", startJoinTime);
        String workerData = eosSyncDataClient.syncNewWorker(token, jsonObject.toJSONString());
        Result<List<NewWorkerClientDTO>> eosResult = JSON.parseObject(workerData, new TypeReference<Result<List<NewWorkerClientDTO>>>() {
        });
        if (eosResult.getCode() != 20216) {
            log.error("新员工同步失败" + eosResult.getMessage());
            throw new AppBusinessException("新员工同步失败");
        }
        List<TbWorker> dbWorkerList = list(new QueryWrapper<TbWorker>().lambda().lt(TbWorker::getWorkerStatus,BusiEnumDefine.WORKER_STATUS_CORRECTED));
        Set<String> dbWorkerIdSet = dbWorkerList.stream().map(TbWorker::getWorkerId).collect(Collectors.toSet());
        Map<String, TbWorker> dbWorkerMap = dbWorkerList.stream().collect(Collectors.toMap(TbWorker::getWorkerId, i -> i));
        List<TbWorker> updateWorkerList = new LinkedList<>();

        List<NewWorkerClientDTO> eosWorkers = eosResult.getData();
        Map<String, NewWorkerClientDTO> eosWorkerMap = eosWorkers.stream().collect(Collectors.toMap(NewWorkerClientDTO::getWorkerId, i -> i));
        Map<String,Set<String>> sendEmailTarget = new HashMap<>(); //接口人邮箱 变更人姓名
        for (NewWorkerClientDTO eosWorker : eosWorkers) {
            if (dbWorkerIdSet.contains(eosWorker.getWorkerId())) {
                SdDept directDept = commService.getDept(eosWorker.getDirectDeptId());
                TbWorker dbWorker = dbWorkerMap.get(eosWorker.getWorkerId());
                if (dbWorker.getWorkerStatus() < BusiEnumDefine.WORKER_STATUS_CORRECTED) {
                    SdAllWorker cacheAllWorker = commService.getAllWorkerDoFromLocalCache(dbWorker.getWorkerId());
                    dbWorker.setDirectDeptId(eosWorker.getDirectDeptId());
                    String[] deptNameChain = directDept.getDeptNameChain().split("/");
                    int length = deptNameChain.length;
                    String dirId ;
                    if(StringUtils.isEmpty(eosWorker.getDirectManager())){
                        dirId = directDept.getDeptManagerId();
                    }else{
                        dirId = eosWorker.getDirectManager();
                    }
                    if (length == 2) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name("");
                        dbWorker.setDept3name("");
                        dbWorker.setDept4name("");
                    } else if (length == 3) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name("");
                        dbWorker.setDept4name("");
                    } else if (length == 4) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name(deptNameChain[3]);
                        dbWorker.setDept4name("");
                    } else if (length == 5) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name(deptNameChain[3]);
                        dbWorker.setDept4name(deptNameChain[4]);
                        SdDept parDept = commService.getDept(directDept.getParentId());
                        String deptManagerId = parDept.getDeptManagerId();
                        if (deptManagerId != null) {
                            dirId = deptManagerId.split(",")[0];
                        }
                    }
                    dbWorker.setPostName(eosWorker.getPostName());
                    dbWorker.setDataSrc(eosWorker.getDataSrc());
                    if (!StringUtils.hasLength(dirId)) {
                        continue;
                    }
                    if (!StringUtils.isEmpty(dbWorker.getDirectManager())) {
                        dirId = dirId.split(",")[0];
                    }
                    if (dbWorker.getChangeDeptManageFlag().equals(TbWorker.changeFlag.NO.getCode())
                            && (StringUtils.hasLength(dbWorker.getDirectManager())
                                && !dirId.equals(dbWorker.getDirectManager().split("/")[1])) ||
                            (dbWorker.getDirectManager() == null && dirId != null)) {
                        //主管不同 且没有手动变更过主管
                        log.info("{}主管不同====",dbWorker.getWorkerId());
                        if (StringUtils.hasLength(dbWorker.getDeptContactor())) {
                            SdAllWorker con = commService.getAllWorkerDoFromLocalCache(dbWorker.getDeptContactor().split(",")[0].split("/")[1]);
                            if (con != null) {
                                log.info("发送邮件====");
                                Set<String> names = sendEmailTarget.get(con.getEmail() + "," + con.getWorkerId() + "," + con.getWorkerName());
                                if (names == null) {
                                    names = new HashSet<>();
                                    names.add(dbWorker.getWorkerName());
                                    sendEmailTarget.put(con.getEmail() + "," + con.getWorkerId() + "," + con.getWorkerName(),names);
                                }else{
                                    names.add(dbWorker.getWorkerName());
                                }
                            }
                        }
                    }
                    dbWorker.setDirectManager(commService.getAllWorkerDoFromLocalCache(dirId).getWorkerName().replace(","," ") + "/" + dirId);
                    updateWorkerList.add(dbWorker);
                }
            }
        }

        Map<String, String> manMap = getManager(updateWorkerList);
        //检查二级主管是否变更
        for (TbWorker tbWorker : updateWorkerList) {
            String secManager = manMap.get(tbWorker.getWorkerId());
            if (notUpdateDept.contains(String.valueOf(tbWorker.getDirectDeptId()))) {
                    //不更新隔级主管的直接更新数据库
                    update(new UpdateWrapper<TbWorker>().lambda().eq(TbWorker::getWorkerId,tbWorker.getWorkerId())
                            .set(TbWorker::getDept1name,tbWorker.getDept1name())
                            .set(TbWorker::getDept2name,tbWorker.getDept2name())
                            .set(TbWorker::getDept3name,tbWorker.getDept3name())
                            .set(TbWorker::getDept4name,tbWorker.getDept4name())
                            .set(TbWorker::getDirectDeptId,tbWorker.getDirectDeptId())
                            .set(tbWorker.getChangeDeptManageFlag().equals(TbWorker.changeFlag.NO.getCode()),TbWorker::getDirectManager,tbWorker.getDirectManager())
                            .set(TbWorker::getPostName,tbWorker.getPostName()));
                    continue;
                }

            if (tbWorker.getChangeSecManageFlag().equals(TbWorker.changeFlag.NO.getCode())
                    && secManager != null && !tbWorker.getSecondManager().contains(secManager)) {
                tbWorker.setSecondManager(secManager);
                //二级主管变更 且隔级主管没有进行手动变更
                SdAllWorker con = commService.getAllWorkerDoFromLocalCache(tbWorker.getDeptContactor().split(",")[0].split("/")[1]);
                if (con != null) {
                    Set<String> names = sendEmailTarget.get(con.getEmail() + "," + con.getWorkerId() + "," + con.getWorkerName());
                    if (names == null) {
                        names = new HashSet<>();
                        names.add(tbWorker.getWorkerName());
                        sendEmailTarget.put(con.getEmail() + "," + con.getWorkerId() + "," + con.getWorkerName(),names);
                    }else{
                        names.add(tbWorker.getWorkerName());
                    }
                }
            }
            update(new UpdateWrapper<TbWorker>().lambda().eq(TbWorker::getWorkerId,tbWorker.getWorkerId())
                    .set(TbWorker::getDept1name,tbWorker.getDept1name())
                    .set(TbWorker::getDept2name,tbWorker.getDept2name())
                    .set(TbWorker::getDept3name,tbWorker.getDept3name())
                    .set(TbWorker::getDept4name,tbWorker.getDept4name())
                    .set(TbWorker::getDirectDeptId,tbWorker.getDirectDeptId())
                    .set(TbWorker::getDataSrc,tbWorker.getDataSrc())
                    .set(tbWorker.getChangeDeptManageFlag().equals(TbWorker.changeFlag.NO.getCode()),TbWorker::getDirectManager,tbWorker.getDirectManager())
                    .set(tbWorker.getChangeSecManageFlag().equals(TbWorker.changeFlag.NO.getCode()),TbWorker::getSecondManager,tbWorker.getSecondManager())
                    .set(TbWorker::getPostName,tbWorker.getPostName()));
        }
        SdEmailTemplate template = emailTemplateService.getById("NOTICE_CON_WORKER_CHANGE");
        List<SdNoticeRecord> sendList = new LinkedList<>();
        for (String s : sendEmailTarget.keySet()) {
            log.info("待发送邮箱:{}",s);
        }
        sendEmailTarget.forEach((key,val) -> {
            String[] split = key.split(",");
            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setCopyToEmail("");
            sdNoticeRecord.setTargetEmail(split[0]);
            sdNoticeRecord.setNoticeContent(template.getEmailTemplateContent().replace("{{workerName}}",val.stream().collect(Collectors.joining(","))));
            sdNoticeRecord.setNoticeTitle(template.getEmailTemplateTitle());
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            sdNoticeRecord.setTargetName(split[2]);
            sdNoticeRecord.setTargetId(split[1]);
            sdNoticeRecord.setCreateTime(new Date());
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId("-1");
            sendList.add(sdNoticeRecord);
        });
        commService.sendMessage(sendList);
    }

    @Override
    @Transactional
    public String syncNewWorker(String time) {
        String token = "Bearer " + userUtils.getToken(eosNemAccount, eosNemPassword);
        String invToken = "Bearer " + userUtils.getToken(inventoryAccount, inventoryAccount);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("entryDate", startJoinTime);
        String workerData = eosSyncDataClient.syncNewWorker(token, jsonObject.toJSONString());
        Result<List<NewWorkerClientDTO>> eosResult = JSON.parseObject(workerData, new TypeReference<Result<List<NewWorkerClientDTO>>>() {
        });
        if (eosResult.getCode() != 20216) {
            log.error("新员工同步失败" + eosResult.getMessage());
            throw new AppBusinessException("新员工同步失败");
        }
        StringBuilder skipWorkerId = new StringBuilder();
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyyMM");
        String startDate = yyyy_MM.format(now);
        List<NewWorkerClientDTO> eosWorkers = eosResult.getData();
        List<TbWorker> dbWorkerList = list();
        Set<String> dbWorkerIdSet = dbWorkerList.stream().map(TbWorker::getWorkerId).collect(Collectors.toSet());
        Map<String, TbWorker> dbWorkerMap = dbWorkerList.stream().collect(Collectors.toMap(TbWorker::getWorkerId, i -> i));
        List<TbOfferWorker> offerWorkerList = offerWorkerService.list();
        Map<String, TbOfferWorker> offerWorkerMap = offerWorkerList.stream().collect(Collectors.toMap(TbOfferWorker::getWorkerId, i -> i));
        List<TbWorker> updateWorkerList = new LinkedList<>();
        List<TbWorker> workerList = new LinkedList<>();
        Calendar calendar = Calendar.getInstance();
        for (NewWorkerClientDTO eosWorker : eosWorkers) {
            //如果员工为9开头则是外籍员工 入职日期不在当前日期 跳过
/*            if (eosWorker.getWorkerId().startsWith("9") || !nowParse.equals(sf.format(eosWorker.getJoinDate()))) {
                continue;
            }*/
            if (eosWorker.getWorkerId().startsWith("9") || (time != null && time.equals(sf.format(eosWorker.getJoinDate())))) {
                continue;
            }
            SdDept directDept = commService.getDept(eosWorker.getDirectDeptId());
            //不存在对应部门 (项目制员工，不参加线上的新员工试用期管理2022/5/16 (周一) 10:18jzy邮件) 跳过
            if (directDept == null) {
                continue;
            }
            if (directDept.getDeptNameChain().contains("代表处服务部/项目交付部") || blockDept.contains(directDept.getDeptId().toString())) {
                continue;
            }
            //已经存在于数据库中 变更部门跟岗位
            if (dbWorkerIdSet.contains(eosWorker.getWorkerId())) {
                TbWorker dbWorker = dbWorkerMap.get(eosWorker.getWorkerId());
                if (dbWorker.getWorkerStatus() < BusiEnumDefine.WORKER_STATUS_CORRECTED) {
                    SdAllWorker cacheAllWorker = commService.getAllWorkerDoFromLocalCache(dbWorker.getWorkerId());
                    dbWorker.setDirectDeptId(cacheAllWorker.getDirectDeptId());
                    String[] deptNameChain = directDept.getDeptNameChain().split("/");
                    int length = deptNameChain.length;
                    if (length == 2) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name("");
                        dbWorker.setDept3name("");
                        dbWorker.setDept4name("");
                    } else if (length == 3) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name("");
                        dbWorker.setDept4name("");
                    } else if (length == 4) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name(deptNameChain[3]);
                        dbWorker.setDept4name("");
                    } else if (length == 5) {
                        dbWorker.setDept1name(deptNameChain[1]);
                        dbWorker.setDept2name(deptNameChain[2]);
                        dbWorker.setDept3name(deptNameChain[3]);
                        dbWorker.setDept4name(deptNameChain[4]);
                    }
                    dbWorker.setPostName(eosWorker.getPostName());
                    updateWorkerList.add(dbWorker);
                }
                continue;
            }
            directDept = commService.getDept(eosWorker.getDirectDeptId());
            //不存在对应部门 (项目制员工，不参加线上的新员工试用期管理2022/5/16 (周一) 10:18jzy邮件) 跳过
            if (directDept == null){
                continue;
            }

            SdAllWorker newWorker = commService.getAllWorkerDoFromLocalCache(eosWorker.getWorkerId());
            if (newWorker == null) {
                log.debug("员工："+eosWorker.getWorkerId()+"/"+eosWorker.getWorkerId()+"目前在allworker中不存在,本次不添加该员工进新员工系统");
                continue;
            }else if (newWorker.getDomainAccount() == null){
                log.error("员工："+eosWorker.getWorkerId()+"/"+eosWorker.getWorkerId()+"目前没有域账号");
                continue;
            }
            eosWorker.setSex(eosWorker.getSex().equals("男") ? "1" : "2");
            TbWorker worker = TbWorkerMap.INSTANCE.clientDTOToWorker(eosWorker);
            worker.setCreateTime(now);

            if(StringUtils.isEmpty(worker.getDirectManager()) && directDept !=null){
                worker.setDirectManager(directDept.getDeptManagerId());
            }
            String[] deptNameChain = directDept.getDeptNameChain().split("/");
            int deptLength = deptNameChain.length;
            if (deptLength == 2) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name("");
                worker.setDept3name("");
                worker.setDept4name("");
            } else if (deptLength == 3) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name("");
                worker.setDept4name("");
            } else if (deptLength == 4) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name(deptNameChain[3]);
                worker.setDept4name("");
            } else if (deptLength == 5) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name(deptNameChain[3]);
                worker.setDept4name(deptNameChain[4]);
                SdDept parDept = commService.getDept(directDept.getParentId());
                String deptManagerId = parDept.getDeptManagerId();
                if (deptManagerId == null) {
                    //部门没有主管
                    log.info("{}对应的部门没有主管", worker.getWorkerId());
                    skipWorkerId.append(worker.getWorkerId()).append(",");
                    continue;
                }
                worker.setDirectManager(deptManagerId.split(",")[0]);
            }
            worker.setDirectManager(commService.getAllWorkerDoFromLocalCache(worker.getDirectManager()).getWorkerName() + "/" + worker.getDirectManager());

            TbOfferWorker offerWorker = offerWorkerMap.get(worker.getWorkerId());
            if (offerWorker != null) {
                worker.setProbationMonth(offerWorker.getProbationMonth());
                calendar.setTime(worker.getJoinDate());
                calendar.add(Calendar.MONTH, offerWorker.getProbationMonth());
                //默认转正时间默认时间+入职时间
                worker.setPassDate(calendar.getTime());
            }

            log.info(eosWorker.getWorkerId()+"/"+eosWorker.getWorkerName()+"："+eosWorker.getSex());
            int sex = eosWorker.getSex().equals("男") ? 1 : 2;
            worker.setSex(sex);

            worker.setWorkerStatus(BusiEnumDefine.WORKER_STATUS_WAIT);
            workerList.add(worker);
        }
        if (workerList.isEmpty()) {
            return skipWorkerId.toString();
        }
        //新员工工号
        List<String> workerIds = workerList.stream().map(TbWorker::getWorkerId).collect(Collectors.toList());
        workerList = setNewWorkerPostName(workerIds, startDate, invToken, workerList);

        Map<String, String> empCodeMap = getEmpCodeMap(workerIds);
        //关联预备员工
        Map<String, TbPreWorker> preWorkerMap;
        if (empCodeMap.isEmpty()) {
            preWorkerMap = new HashMap<>();
        } else {
            List<TbPreWorker> preWorkerList = preWorkerService.list(new QueryWrapper<TbPreWorker>().in("pre_worker_id", empCodeMap.values()));
            //workerId->preWorker
            preWorkerMap = preWorkerList.stream().collect(Collectors.toMap(TbPreWorker::getPreWorkerId, i -> i));
        }
        Map<String, String> devGrade = getDevGrade(workerIds);
        JSONObject grade = psaClient.getGrade(workerIds);
        //成绩查询失败
        /*if (!(boolean)grade.get("success")) {
            log.error("同步失败：新员工成绩查询失败" + grade.get("message").toString());
            throw new AppBusinessException("新员工同步失败：新员工成绩查询失败");
        }*/
        //id->grade
        Map<String, Object> gradeMap = (Map<String, Object>) grade.get("data");
        //给新员工加上成绩
        workerList.forEach(item -> {
            String preWorkerId = empCodeMap.get(item.getWorkerId());
            TbPreWorker preWorker = preWorkerMap.get(preWorkerId);
            if (preWorker != null) {
                item.setTeacherInfo(preWorker.getTeacherInfo());
                item.setDirectManager(preWorker.getDirectManager());
                item.setProbationMonth(preWorker.getProbationMonth());
                calendar.setTime(item.getJoinDate());
                calendar.add(Calendar.MONTH, planProbationMonth);
                item.setPassDate(calendar.getTime());
            }
            if (gradeMap != null) {
                Object newExamScore = gradeMap.get(item.getWorkerId());
                if (newExamScore != null) {
                    item.setNewExamScore(BigDecimal.valueOf((Double) newExamScore).setScale(1, BigDecimal.ROUND_HALF_UP));
                }
            }
            String devG = devGrade.get(item.getWorkerId());
            item.setYanScore(devG == null ? null : Double.parseDouble(devG));
        });

        //获取隔级主管
        Map<String, String> manager = getManager(workerList);

        TodoTaskNodeEnum orderStatusEnum = TodoTaskNodeEnum.getEnumByValue(BusiEnumDefine.FLOW_STATUS_NEW_WORKRR_NOTICE);
        //格式存放的主管信息
        Set<String> sendBpDeptContectMap = new HashSet<>();
        List<SdTodoTask> tasks = new ArrayList<>();
        for (TbWorker tbWorker : workerList) {
            tbWorker.setSecondManager(manager.get(tbWorker.getWorkerId()));
            //隔级主管是于总 转正考核人存放直接主管
            if (StringUtils.hasLength(tbWorker.getDept3name()) && tbWorker.getSecondManager().contains("68001")) {
                tbWorker.setFinalJudger(tbWorker.getDirectManager());
            }else{
                tbWorker.setFinalJudger(tbWorker.getSecondManager());
            }
/*            tbWorker.setDirectManager(tbWorker.getDirectManager().replace(","," "));
            tbWorker.setSecondManager(tbWorker.getSecondManager().replace(","," "));*/
            //第一考核人默认思想导师  最终考核人默认直接主管 最终评价人默认隔级主管
            tbWorker.setFirstApprover(tbWorker.getTeacherInfo());
            tbWorker.setFinalApprover(tbWorker.getDirectManager());
            // 三级主管及以下不到于总
            SdDept directDept = commService.getDept(tbWorker.getDirectDeptId());
            String contactors = null;
            String cityContactor = directDept.getCityContactor();
            boolean getCon = false;
            if (!StringUtils.isEmpty(cityContactor)) {
                String[] cityContactors = cityContactor.split(";");
                for (String contactorId : cityContactors) {
                    String[] city_ConId = contactorId.split(":");
                    if (city_ConId[0].equals(tbWorker.getWorkCity())) {
                        contactors = city_ConId[1];
                        getCon = true;
                        break;
                    }
                }
            }
            if (!getCon && !StringUtils.isEmpty(directDept.getContactorId())) {
                contactors = directDept.getContactorId().split(",")[0];
            }
            String bpUserId = directDept.getBpUserId();
            SdAllWorker newWorker = commService.getAllWorkerDoFromLocalCache(tbWorker.getWorkerId());
            if (newWorker != null) {
                tbWorker.setJobLevel(newWorker.getJobLevel());
                tbWorker.setJobType(newWorker.getJobType());
            } else {
                continue;
            }
            if (!StringUtil.isEmpty(contactors)) {
                String[] contactIds = contactors.split(",");
                StringBuilder sb = new StringBuilder();
                int i = 0;
                for (String item : contactIds) {
                    if (i != 0) {
                        sb.append(",");
                    }
                    SdAllWorker contactor = commService.getAllWorkerDoFromLocalCache(item);
                    if (contactor != null) {
                        sb.append(contactor.getWorkerName()).append("/").append(contactor.getWorkerId());
                        i++;
                    }else{
                        log.error("缓存取不到接口人信息");
                        SdAllWorker byId = allWorkerService.getById(item);
                        sb.append(byId.getWorkerName()).append("/").append(byId.getWorkerId());
                        i++;
                    }
                }
                if (sb.length() == 0) {
                    log.error("缓存取不到接口人信息");
                }
                tbWorker.setDeptContactor(sb.toString());
            }else{
                log.error("部门上没有接口人");
            }
            //构建接口人待办
            if (newWorker != null && newWorker.getJobLevel() != null && Integer.parseInt(newWorker.getJobLevel()) >= 18) {
                sendBpDeptContectMap.add(directDept.getGbbzId());
                SdAllWorker gbbz = commService.getAllWorkerDoFromLocalCache(directDept.getGbbzId());
                if (gbbz != null) {
                    SdTodoTask task = createTask(IdWorker.nextId() + "", newWorker.getWorkerId(), gbbz.getWorkerId(),
                            BusiEnumDefine.FLOW_NEW_WORKER_NOTICE, orderStatusEnum.getName(), orderStatusEnum.toString(),
                            BusiEnumDefine.FLOW_NEW_IN);
                    tasks.add(task);
                }
            } else {
                if (!StringUtil.isEmpty(bpUserId)) {
                    sendBpDeptContectMap.addAll(Arrays.asList(bpUserId.split(",")));
                }
                if (newWorker != null && !StringUtil.isEmpty(contactors)) {
                    SdTodoTask task = createTask(IdWorker.nextId() + "",
                            newWorker.getWorkerId(),
                            contactors,
                            BusiEnumDefine.FLOW_NEW_WORKER_NOTICE,
                            tbWorker.getWorkerId() + "的" + orderStatusEnum.getName(),
                            orderStatusEnum.toString(),
                            BusiEnumDefine.FLOW_NEW_IN);
                    tasks.add(task);
                    sendBpDeptContectMap.addAll(Arrays.asList(contactors.split(",")));
                }

            }
        }
        saveOrUpdateBatch(workerList);
        /*updateWorkerList.forEach(i -> update(new UpdateWrapper<TbWorker>().lambda()
                .eq(TbWorker::getWorkerId,i.getWorkerId())
                .set(TbWorker::getDept1name,i.getDept1name())
                .set(TbWorker::getDept2name,i.getDept2name())
                .set(TbWorker::getDept3name,i.getDept3name())
                .set(TbWorker::getDept4name,i.getDept4name())
                .set(TbWorker::getDirectDeptId, i.getDirectDeptId())
                .set(TbWorker::getPostName,i.getPostName())));*/
        SdEmailTemplate emailTemplate = emailTemplateService.getById("NEW_WORKER_IN");

        List<SdNoticeRecord> sendList = new LinkedList<>();
        sendBpDeptContectMap.forEach(i -> {
            SdAllWorker BP = commService.getAllWorkerDoFromLocalCache(i);
            if (BP != null) {
                SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
                sdNoticeRecord.setCopyToEmail("");
                sdNoticeRecord.setTargetEmail(BP.getEmail());
                sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
                sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
                sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                sdNoticeRecord.setTargetName(BP.getWorkerName());
                sdNoticeRecord.setTargetId(BP.getWorkerId());
                sdNoticeRecord.setCreateTime(new Date());
                sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
                sdNoticeRecord.setFlowId("BPNOTICE");
                sendList.add(sdNoticeRecord);
            }
        });
        todoTaskService.saveBatch(tasks);
        commService.sendMessage(sendList);
        tasks.forEach(i -> todoTaskService.sendTodoTask(i));
        return skipWorkerId.toString();
    }

    @Override
    @Transactional
    public void syncNewWorkerGrade(){
        Date now = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(now);
        instance.set(Calendar.MONTH, -7);
        Date conditionDate= instance.getTime();
        List<TbWorker> workerList = list(new QueryWrapper<TbWorker>().lambda()
                .isNull(TbWorker::getNewExamScore)
                .or()
                .isNull(TbWorker::getYanScore)
                .or()
                .ge(TbWorker::getJoinDate, conditionDate));
        List<String> workerIds = workerList.stream().map(TbWorker::getWorkerId).collect(Collectors.toList());
        //获取研发成绩
        Map<String, String> devGrade = getDevGrade(workerIds);
        //获取新员工成绩
        JSONObject grade = psaClient.getGrade(workerIds);
        //成绩查询失败
        /*if (!(boolean)grade.get("success")) {
            log.error("同步失败：新员工成绩查询失败" + grade.get("message").toString());
            throw new AppBusinessException("新员工同步失败：新员工成绩查询失败");
        }*/
        //id->grade
        Map<String, Object> gradeMap = (Map<String, Object>) grade.get("data");
        List<TbWorker> updateWorkerList = new LinkedList<>();
        boolean hasGrade;
        boolean hasYan;
        for (TbWorker item : workerList) {
            hasGrade = false;
            hasYan = false;
            if (gradeMap != null) {
                Object newExamScore = gradeMap.get(item.getWorkerId());
                if (newExamScore != null) {
                    item.setNewExamScore(BigDecimal.valueOf(Double.parseDouble(newExamScore.toString())).setScale(1, BigDecimal.ROUND_HALF_UP));
                    hasGrade = true;
                }
            }
            String devG = devGrade.get(item.getWorkerId());
            if (devG != null) {
                item.setYanScore(Double.parseDouble(devG));
                hasYan = true;
            }
            if (hasGrade || hasYan) {
                TbWorker upWorker = new TbWorker();
                upWorker.setWorkerId(item.getWorkerId());
                upWorker.setYanScore(item.getYanScore());
                upWorker.setNewExamScore(item.getNewExamScore());
                updateWorkerList.add(upWorker);
            }
        }
        updateBatchById(updateWorkerList);
    }

    public List<TbWorker> setNewWorkerPostName(List<String> workerIds, String statDate, String midToken, List<TbWorker> workerList){
        Map<String, TbWorker> workerMap = workerList.stream().collect(Collectors.toMap(k -> k.getWorkerId(), val -> val));
        String[] workerArray = workerIds.toArray(new String[workerIds.size()]);
        JSONObject workerInfoJson = new JSONObject();
        workerInfoJson.put("empCode", workerArray);
        workerInfoJson.put("statDate", statDate);
        String workerInfos = eosSyncDataClient.getWorkerInfo(midToken, workerInfoJson.toJSONString());
        log.info("获取新员工岗位名称:  " + workerInfos);
        Result<List<WorkerInfoClientDTO>> workerInfosResult = JSON.parseObject(workerInfos, new TypeReference<Result<List<WorkerInfoClientDTO>>>() {
        });

        if(workerInfosResult!=null && workerInfosResult.getData()!=null){
            workerInfosResult.getData().forEach(worker ->{
                String workerId = worker.getWorkerId();
                TbWorker tbWorker = workerMap.get(workerId);
                if(tbWorker!=null){
                    tbWorker.setPostName(worker.getPostName());
                }
            });
        }
        return new ArrayList<TbWorker>(workerMap.values());
    }

    @Override
    @Transactional
    public void syncNewWorker1(String time) {
        String token = "Bearer " + userUtils.getToken(eosNemAccount, eosNemPassword);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("entryDate", startJoinTime);
        String workerData = eosSyncDataClient.syncNewWorker(token, jsonObject.toJSONString());
        Result<List<NewWorkerClientDTO>> eosResult = JSON.parseObject(workerData, new TypeReference<Result<List<NewWorkerClientDTO>>>() {
        });
        if (eosResult.getCode() != 20216) {
            log.error("新员工同步失败" + eosResult.getMessage());
            throw new AppBusinessException("新员工同步失败");
        }
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyyMM");
        String statDate = yyyy_MM.format(now);
        List<NewWorkerClientDTO> eosWorkers = eosResult.getData();
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        List<TbWorker> dbWorkerList = list();
        Map<String,TbWorker> dbWorkerIdMap = dbWorkerList.stream().collect(Collectors.toMap(TbWorker::getWorkerId, i->i));
        List<TbWorker> workerList = new LinkedList<>();
        Calendar calendar = Calendar.getInstance();
        for (NewWorkerClientDTO eosWorker : eosWorkers) {
            //如果员工为9开头则是外籍员工 入职日期不在当前日期 跳过
/*            if (eosWorker.getWorkerId().startsWith("9") || !nowParse.equals(sf.format(eosWorker.getJoinDate()))) {
                continue;
            }*/
            if (eosWorker.getWorkerId().startsWith("9") || (time != null && time.equals(sf.format(eosWorker.getJoinDate())))) {
                continue;
            }
            //已经存在于数据库中跳过
           /* if (dbWorkerIdSet.contains(eosWorker.getWorkerId())) {
                continue;
            }
*/
            TbWorker dbW = dbWorkerIdMap.get(eosWorker.getWorkerId());
            if (dbW != null && dbW.getWorkerStatus() != BusiEnumDefine.WORKER_STATUS_WAIT) {
                continue;
            }

            SdAllWorker newWorker = (SdAllWorker) dataCacheMap.get("allworker-" + eosWorker.getWorkerId());
            if (newWorker == null) {
                continue;
            }
            eosWorker.setSex(eosWorker.getSex().equals("男") ? "1" : "2");
            TbWorker worker = TbWorkerMap.INSTANCE.clientDTOToWorker(eosWorker);
//            worker.setCreateTime(now);
            SdDept directDept = (SdDept) dataCacheMap.get("dept-" + eosWorker.getDirectDeptId());
            if(StringUtils.isEmpty(worker.getDirectManager()) && directDept !=null){
                worker.setDirectManager(directDept.getDeptManagerId());
            }
            String[] deptNameChain = directDept.getDeptNameChain().split("/");
            int deptLength = deptNameChain.length;
            if (deptLength == 2) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name("");
                worker.setDept3name("");
                worker.setDept4name("");
            } else if (deptLength == 3) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name("");
                worker.setDept4name("");
            } else if (deptLength == 4) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name(deptNameChain[3]);
                worker.setDept4name("");
            } else if (deptLength == 5) {
                worker.setDept1name(deptNameChain[1]);
                worker.setDept2name(deptNameChain[2]);
                worker.setDept3name(deptNameChain[3]);
                worker.setDept4name(deptNameChain[4]);
                SdDept parDept = (SdDept) dataCacheMap.get("dept-" + directDept.getParentId());
                worker.setDirectManager(parDept.getDeptManagerId());
            }
            worker.setProbationMonth(planProbationMonth);
            calendar.setTime(worker.getJoinDate());
            calendar.add(Calendar.MONTH, planProbationMonth);
            //默认转正时间默认时间+入职时间
            worker.setPassDate(calendar.getTime());
            int sex = eosWorker.getSex().equals("男") ? 1 : 2;
            worker.setSex(sex);

            worker.setWorkerStatus(BusiEnumDefine.WORKER_STATUS_WAIT);
            workerList.add(worker);
        }
        if (workerList.isEmpty()) {
            return;
        }
        //新员工工号
        List<String> workerIds = workerList.stream().map(TbWorker::getWorkerId).collect(Collectors.toList());
        //设置新员工岗位名称
        workerList = setNewWorkerPostName(workerIds, statDate, token, workerList);
        Map<String, String> empCodeMap = getEmpCodeMap(workerIds);
        //关联预备员工
        Map<String, TbPreWorker> preWorkerMap;
        if (empCodeMap.isEmpty()) {
            preWorkerMap = new HashMap<>();
        } else {
            List<TbPreWorker> preWorkerList = preWorkerService.list(new QueryWrapper<TbPreWorker>().in("pre_worker_id", empCodeMap.values()));
            //workerId->preWorker
            preWorkerMap = preWorkerList.stream().collect(Collectors.toMap(TbPreWorker::getPreWorkerId, i -> i));
        }
        Map<String, String> devGrade = getDevGrade(workerIds);
        JSONObject grade = psaClient.getGrade(workerIds);
        //成绩查询失败
        /*if (!(boolean)grade.get("success")) {
            log.error("同步失败：新员工成绩查询失败" + grade.get("message").toString());
            throw new AppBusinessException("新员工同步失败：新员工成绩查询失败");
        }*/
        //id->grade
        Map<String, Object> gradeMap = (Map<String, Object>) grade.get("data");
        //给新员工加上成绩
        workerList.forEach(item -> {
            String preWorkerId = empCodeMap.get(item.getWorkerId());
            TbPreWorker preWorker = preWorkerMap.get(preWorkerId);
            if (preWorker != null) {
                item.setTeacherInfo(preWorker.getTeacherInfo());
                if(!StringUtils.isEmpty(preWorker.getDirectManager())){
                    item.setDirectManager(preWorker.getDirectManager());
                }
                item.setProbationMonth(preWorker.getProbationMonth());
                calendar.setTime(item.getJoinDate());
                calendar.add(Calendar.MONTH, planProbationMonth);
                item.setPassDate(calendar.getTime());
            }
            if (gradeMap != null) {
                Object newExamScore = gradeMap.get(item.getWorkerId());
                if (newExamScore != null) {
                    item.setNewExamScore(BigDecimal.valueOf((Double) newExamScore).setScale(1, BigDecimal.ROUND_HALF_UP));
                }
            }
            String devG = devGrade.get(item.getWorkerId());
            item.setYanScore(devG == null ? null : Double.parseDouble(devG));
        });
        //获取主管map
        Map<String, WorkerInfoClientDTO> firMangerMap = getManager(workerList,statDate,token);
        //格式存放的主管信息
        Set<String> sendBpDeptContectMap = new HashSet<>();
        for (TbWorker tbWorker : workerList) {
            WorkerInfoClientDTO firManager = firMangerMap.get(tbWorker.getDirectManager());
            if (firManager != null) {
                tbWorker.setDirectManager(firManager.getWorkerName() + "/" + firManager.getWorkerId());
                //主管不存在主管 隔级主管为主管
                if (firManager.getDirectManager() == null) {
                    tbWorker.setSecondManager(firManager.getWorkerName() + "/" + firManager.getWorkerId());
                } else {
                    SdAllWorker secManager = (SdAllWorker) dataCacheMap.get("allworker-" + firManager.getDirectManager());
                    if (secManager != null) {
                        tbWorker.setSecondManager(secManager.getWorkerName() + "/" + secManager.getWorkerId());
                    }
                }
            }
            //第一考核人默认思想导师  最终考核人默认直接主管 最终评价人默认隔级主管
            /*tbWorker.setFirstApprover(tbWorker.getTeacherInfo());
            tbWorker.setFinalApprover(tbWorker.getDirectManager());
            tbWorker.setFinalJudger(tbWorker.getSecondManager());*/
            SdDept directDept = (SdDept) dataCacheMap.get("dept-" + tbWorker.getDirectDeptId());
            String contactors = null;
            String cityContactor = directDept.getCityContactor();
            boolean getCon = false;
            if (!StringUtils.isEmpty(cityContactor)) {
                String[] cityContactors = cityContactor.split(";");
                for (String contactorId : cityContactors) {
                    String[] city_ConId = contactorId.split(":");
                    if (city_ConId[0].equals(tbWorker.getWorkCity())) {
                        contactors = city_ConId[1];
                        getCon = true;
                        break;
                    }
                }
            }
            if (!getCon && !StringUtils.isEmpty(directDept.getContactorId())) {
                contactors = directDept.getContactorId().split(",")[0];
            }
            String bpUserId = directDept.getBpUserId();
            SdAllWorker newWorker = (SdAllWorker) dataCacheMap.get("allworker-" + tbWorker.getWorkerId());
            if (newWorker != null) {
                tbWorker.setJobLevel(newWorker.getJobLevel());
                tbWorker.setJobType(newWorker.getJobType());
            } else {
                continue;
            }
            if (!StringUtil.isEmpty(contactors)) {
                String[] contactIds = contactors.split(",");
                StringBuilder sb = new StringBuilder();
                int i = 0;
                for (String item : contactIds) {
                    if (i != 0) {
                        sb.append(",");
                    }
                    SdAllWorker contactor = (SdAllWorker) dataCacheMap.get("allworker-" + item);
                    sb.append(contactor.getWorkerName()).append("/").append(contactor.getWorkerId());
                    i++;
                }
                tbWorker.setDeptContactor(sb.toString());
            }

            if (newWorker != null && Integer.parseInt(newWorker.getJobLevel()) >= 18) {
                sendBpDeptContectMap.add(directDept.getGbbzId());
                SdAllWorker gbbz = (SdAllWorker) dataCacheMap.get("allworker-" + directDept.getGbbzId());
                if (gbbz != null) {
                    /*initTodoTask(IdWorker.nextId() + "", newWorker.getWorkerId(), gbbz.getWorkerId(),
                            BusiEnumDefine.FLOW_NEW_WORKER_NOTICE, orderStatusEnum.getName(), orderStatusEnum.toString(),
                            BusiEnumDefine.FLOW_NEW_IN);*/
                }
            } else {
                if (!StringUtil.isEmpty(bpUserId)) {
                    sendBpDeptContectMap.addAll(Arrays.asList(bpUserId.split(",")));
                }
                if (newWorker != null && !StringUtil.isEmpty(contactors)) {
                    /*initTodoTask(IdWorker.nextId() + "",
                            newWorker.getWorkerId(),
                            contactors,
                            BusiEnumDefine.FLOW_NEW_WORKER_NOTICE,
                            tbWorker.getWorkerId() + "的" + orderStatusEnum.getName(),
                            orderStatusEnum.toString(),
                            BusiEnumDefine.FLOW_NEW_IN);*/
                    sendBpDeptContectMap.addAll(Arrays.asList(contactors.split(",")));
                }

            }
        }
//        SdEmailTemplate emailTemplate = emailTemplateService.getById("NEW_WORKER_IN");
//
//        List<SdNoticeRecord> sendList = new LinkedList<>();
//        sendBpDeptContectMap.forEach(i -> {
//            SdAllWorker BP = (SdAllWorker) dataCacheMap.get("allworker-" + i);
//            if (BP != null) {
//                SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
//                sdNoticeRecord.setCopyToEmail("");
//                sdNoticeRecord.setTargetEmail(BP.getEmail());
//                sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
//                sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
//                sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
//                sdNoticeRecord.setTargetName(BP.getWorkerName());
//                sdNoticeRecord.setTargetId(BP.getWorkerId());
//                sdNoticeRecord.setCreateTime(new Date());
//                sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
//                sdNoticeRecord.setFlowId("BPNOTICE");
//                sendList.add(sdNoticeRecord);
//            }
//        });
//        commService.sendMessage(sendList);
        saveOrUpdateBatch(workerList);
    }

    /**
     * 获取员工的主管
     * @param workerList
     * @param startDate
     * @param token
     * @return
     */
    private Map<String,WorkerInfoClientDTO> getManager(List<TbWorker> workerList,String startDate,String token){
        //根据新员工的直接主管，获取隔级主管工号
        List<String> directManagerIds = workerList.stream()
                .map(TbWorker::getDirectManager)
                .distinct()
                .collect(Collectors.toList());
        //获取四级主管的上级主管
        String[] managerArray = directManagerIds.toArray(new String[directManagerIds.size()]);
        JSONObject workerInfoJson = new JSONObject();
        workerInfoJson.put("empCode", managerArray);
        workerInfoJson.put("statDate", startDate);
        String managerInfos = eosSyncDataClient.getWorkerInfo(token, workerInfoJson.toJSONString());
        log.info("获取四级主管的上级主管:  " + managerInfos);
        Result<List<WorkerInfoClientDTO>> managerInfosResult = JSON.parseObject(managerInfos, new TypeReference<Result<List<WorkerInfoClientDTO>>>() {
        });
        if (!managerInfosResult.getFlag() || managerInfosResult.getCode() != 20216) {
            log.error("新员工同步失败：获取主管信息失败" + managerInfosResult.getMessage());
            throw new AppBusinessException("新员工同步失败");
        }
        List<WorkerInfoClientDTO> managerData = managerInfosResult.getData();
        HashMap<String,WorkerInfoClientDTO> firMangerMap = new HashMap<>();
        String nowManagerId = "";
        for (WorkerInfoClientDTO manager : managerData) {
            //返回的员工信息一个人可能有多个 取第一个
            if (!nowManagerId.equals(manager.getWorkerId())) {
               /* String secWorkerId = manager.getDirectManager() == null ? nowManagerId : manager.getDirectManager();
                for (TbWorker worker : workerList) {
                    //员工的主管存在，
                    if (worker.getDirectManager() != null && worker.getDirectDeptId().toString().equals(nowManagerId)) {
                        worker.setSecondManager(secWorkerId);
                    }
                }*/
                manager.setWorkerName(manager.getWorkerName().replace(","," "));
                nowManagerId = manager.getWorkerId();
                firMangerMap.put(nowManagerId,manager);
            }
        }
        return firMangerMap;
    }

    /**
     * 根据部门获取隔级主管
     * @param workerList
     * @return
     */
    private Map<String, String> getManager(List<TbWorker> workerList){
        Map<String, String> manMap = new HashMap<>();
        for (TbWorker tbWorker : workerList) {
            Integer directDeptId = tbWorker.getDirectDeptId();
            SdDept dept = commService.getDept(directDeptId);
            if (dept.getDeptLevel() == 4) {
                //最小直接主管是三级主管
                dept = commService.getDept(dept.getParentId());
            }
            if (dept.getDeptLevel() == 1) {
                manMap.put(tbWorker.getWorkerId(), tbWorker.getDirectManager());
            }else{
                SdDept parDept = commService.getDept(dept.getParentId());
                Assert.notNull(parDept);
                if (parDept.getDeptManagerName() == null) {
                    manMap.put(tbWorker.getWorkerId(), "");
                }else{
                    manMap.put(tbWorker.getWorkerId(), parDept.getDeptManagerName().split(",")[0]);
                }
            }
        }
        return manMap;
    }

    private Map<String, String> getEmpCodeMap(List<String> workerIds) {
        Map<String, String> resMap = new HashMap<>();

        String sapToken = commService.getSapToken(hrssUId, hrssPasswd);
        if (sapToken == null) {
            return resMap;
        }
        JSONObject jo = new JSONObject();
        jo.put("EmpCode", workerIds.toArray());
        JSONObject empCodeMap = sapClient.empCodeMaps(jo.toJSONString(), sapToken);
        boolean success = (boolean) empCodeMap.get("success");
        if (success) {
            ArrayList data = (ArrayList) empCodeMap.get("data");
            for (Object datum : data) {
                Map<String, String> dataMap = (Map<String, String>) datum;
                resMap.put(dataMap.get("EmpCode"), dataMap.get("HC_NO"));
            }
        }
        return resMap;
    }

    private Map<String, String> getDevGrade(List<String> newWorkerIds) {
        if (newWorkerIds == null || newWorkerIds.isEmpty()) {
            return new HashMap<>();
        }
        Map<String, String> resMap = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        int i = 0;
        int size = newWorkerIds.size();
        for (String newWorkerId : newWorkerIds) {
            stringBuilder.append("'").append(newWorkerId).append("'");
            if (i++ != size -1) {
                stringBuilder.append(",");
            }
        }
        String ids = stringBuilder.toString();
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager
                    .getConnection(postgresUrl,
                            postgresUsername, postgresPassword);
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("select user_code,max(grade_score) grade,exam_name" +
                    "       from rd_manage_view where user_code in (" + ids + ") " +
                    "       AND exam_code = 'TXRZ-A001' GROUP BY exam_name, user_code ORDER BY grade DESC;");
            while (rs.next()) {
                String examName = rs.getString("exam_name");
                if (examName != null && examName.contains("非研发")) {
                    continue;
                }
                if (resMap.containsKey(rs.getString("user_code"))) {
                    continue;
                }
                resMap.put(rs.getString("user_code"), rs.getString("grade"));
            }
            rs.close();
            stmt.close();
            c.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new AppBusinessException("获取研发成绩失败：" + e.getMessage());
        }
        return resMap;
    }

    @Override
    public void importWorkerList(MultipartFile file) {
        String excelJsonString = commService.parseExcelByTemplate(BusiEnumDefine.NEW_WORKER_EXPORT, file);
        List<TbWorkerDTO> tbWorkers = JSONArray.parseArray(excelJsonString, TbWorkerDTO.class);
        for (TbWorkerDTO i : tbWorkers) {
            if (StringUtils.isEmpty(i.getWorkerName())) {
                continue;
            }
            i.setWorkerId(i.getWorkerName().split("/")[1]);
            if (!StringUtils.isEmpty(i.getDeptContactor())) {
                String deptContactor = "";
                String[] split = i.getDeptContactor().split(",");
                for (String s : split) {
                    deptContactor = deptContactor.concat(s.split("/")[1]).concat(",");
                }
                i.setDeptContactor(deptContactor.substring(0, deptContactor.length() - 1));
            }
            if (!StringUtils.isEmpty(i.getTeacherInfo())) {
                i.setTeacherInfo(i.getTeacherInfo().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getDirectManager())) {
                i.setDirectManager(i.getDirectManager().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getFinalApprover())) {
                i.setFinalApprover(i.getFinalApprover().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getFirstApprover())) {
                i.setFirstApprover(i.getFirstApprover().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getSecondApprover())) {
                i.setSecondApprover(i.getSecondApprover().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getThirdApprover())) {
                i.setThirdApprover(i.getThirdApprover().split("/")[1]);
            }
            if (!StringUtils.isEmpty(i.getFinalJudger())) {
                i.setFinalJudger(i.getFinalJudger().split("/")[1]);
            }
            updateDto(i);
        }
    }

    @Override
    public void endAssessment(List<TbWorkerDTO> paramsDTOS) {
        List<String> workerIds = paramsDTOS.stream().map(TbWorkerDTO::getWorkerId).collect(Collectors.toList());
        String operateNote = paramsDTOS.get(0).getOperateNote();
        Date now = new Date();
        List<TbWorker> dbWorkers = list(new QueryWrapper<TbWorker>().lambda()
                .in(TbWorker::getWorkerId, workerIds)
                .notIn(TbWorker::getWorkerStatus,BusiEnumDefine.WORKER_STATUS_ELIMINATED,BusiEnumDefine.WORKER_STATUS_CORRECTED,BusiEnumDefine.WORKER_STATUS_TERMINATED));
        List<SdAllWorker> sdAllWorkers = new ArrayList<>();
        for (TbWorker tbWorker : dbWorkers) {
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(tbWorker.getWorkerId());
            if (sdAllWorker != null) {
                sdAllWorkers.add(sdAllWorker);
            }
        }
        List<String> accountList = sdAllWorkers.stream().map(SdAllWorker::getDomainAccount).collect(Collectors.toList());
        List<String> excWorkerIds = dbWorkers.stream().map(TbWorker::getWorkerId).collect(Collectors.toList());
        //更新员工状态
        update(new UpdateWrapper<TbWorker>()
                .set("worker_status", BusiEnumDefine.WORKER_STATUS_TERMINATED)
                .in("worker_id", excWorkerIds));
        List<TbTeachSchedule> tbTeachSchedules = teachScheduleMapper.selectList(new QueryWrapper<TbTeachSchedule>().lambda().in(TbTeachSchedule::getWorkerId, excWorkerIds));
        for (TbTeachSchedule exc : tbTeachSchedules) {
            if (exc.getEndDate() == null) {
                exc.setEndDate(new Date());
            }
            exc.setAllowanceFlag(TbTeachSchedule.AllowanceFlag.CAN.getFlag());
            teachScheduleMapper.update(exc,new UpdateWrapper<TbTeachSchedule>().lambda()
                    .eq(TbTeachSchedule::getWorkerId,exc.getWorkerId()));
        }

        //关闭流程
        List<TbFlowInst> flowInstList = tbFlowInstService.list(new QueryWrapper<TbFlowInst>().in("worker_id", excWorkerIds)
                .isNull("finish_time"));
        if (!CollectionUtils.isEmpty(flowInstList)) {
//            throw new AppBusinessException("没有找到需要终止的在途流程");
            //启动考核的人员
            //关闭待办
            List<String> flowIdList = flowInstList.stream().map(TbFlowInst::getFlowId).collect(Collectors.toList());
            tbFlowInstService.update(new UpdateWrapper<TbFlowInst>()
                    .set("finish_time", now)
                    .set("flow_note", operateNote)
                    .set("current_stage", BusiEnumDefine.currentStageTermination)
                    .set("flow_status", BusiEnumDefine.flowStatusTermination)
                    .in("flow_id", flowIdList));
            //对终止的每个在途流程，查一条类型为终止的审批记录
            flowInstList.forEach(flowInstObj -> {
                TbFlowInstDTO flowInstDTO = new TbFlowInstDTO();
                flowInstDTO.setFlowId(flowInstObj.getFlowId());
                flowInstDTO.setArriveTime(flowInstObj.getArriveTime());
                tbFlowInstServiceImpl.setApprovalRecord(flowInstDTO, BusiEnumDefine.APPROVAL_TYPE_TERMINAL, operateNote);
            });
            List<SdTodoTask> todoTaskList2 = todoTaskService.list(new QueryWrapper<SdTodoTask>().in("docunid", flowIdList));
            for (SdTodoTask sdTodoTask : todoTaskList2) {
                sdTodoTask.setEnduserid(sdTodoTask.getEnduserid() + commService.getLoginUserDTO().getAccount());
                sdTodoTask.setAuthorid("");
                sdTodoTask.setAuthorname("");
                sdTodoTask.setNodeid("TERMINATION");
                sdTodoTask.setNodename("已终止");
                sdTodoTask.setStatus("APPROVED");
                todoTaskService.sendTodoTask(sdTodoTask);
            }
        }

        //关闭待办
        List<SdTodoTask> todoTaskList = todoTaskService.list(new QueryWrapper<SdTodoTask>().lambda().in(SdTodoTask::getAdduserid, accountList));
        for (SdTodoTask sdTodoTask : todoTaskList) {
            if("APPROVING".equals(sdTodoTask.getStatus())){
                sdTodoTask.setEnduserid(sdTodoTask.getEnduserid() + commService.getLoginUserDTO().getAccount());
                sdTodoTask.setAuthorid("");
                sdTodoTask.setAuthorname("");
                sdTodoTask.setNodeid("TERMINATION");
                sdTodoTask.setNodename("已终止");
                sdTodoTask.setStatus("APPROVED");
                todoTaskService.sendTodoTask(sdTodoTask);
            }
        }

    }

    @Override
    public List<Map<String, Object>> get2WePassedWorkerList(Date startTime, Date endTime, Set<Integer> deptIdList, boolean isMore18, String conId) {
        return tbWorkerMapper.get2WePassedWorkerList(startTime, endTime, deptIdList, isMore18, conId);
    }

    @Override
    public void sendRegularNotice(SdEmailTemplateDTO emailTemplateDTO) {
        String loginUserId = commService.getLoginUserId();
        for (String workerId : emailTemplateDTO.getWaitSendWorkerId()) {
            SdAllWorker worker = (SdAllWorker) CommService.dataCacheMap.get("allworker-" + workerId);
            SdNoticeRecord toTeacherRecord = new SdNoticeRecord();
            toTeacherRecord.setNoticeId(IdWorker.nextId() + "");
            toTeacherRecord.setFlowId(IdWorker.nextId() + "");
            toTeacherRecord.setApplyUserId(loginUserId);
            toTeacherRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            toTeacherRecord.setTargetId(worker.getWorkerId());
            toTeacherRecord.setTargetName(worker.getWorkerName());
            toTeacherRecord.setTargetEmail(worker.getEmail());
            toTeacherRecord.setNoticeTitle(emailTemplateDTO.getEmailTemplateTitle());
            toTeacherRecord.setNoticeContent(emailTemplateDTO.getEmailTemplateContent());
            toTeacherRecord.setCreateTime(new Date());
            commService.sendMessage(toTeacherRecord);
        }
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(TbWorkerDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = IdWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return tbWorkerMapper.insertTbWorker(JSONObject.parseObject(JSON.toJSONString(dto), TbWorker.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(TbWorkerDTO dto) {
        Integer probationMonth = dto.getProbationMonth();
        if (probationMonth < 3) {
            throw new AppBusinessException("试用期不能低于3个月");
        }
        if (probationMonth > 6) {
            throw new AppBusinessException("试用期不能大于6个月");
        }
        int total = 0;
        Set<String> approver = new HashSet<>();
        if (!StringUtils.isEmpty(dto.getFirstApprover())) {
            approver.add(dto.getFirstApprover());
            total++;
        }
        if (!StringUtils.isEmpty(dto.getSecondApprover())) {
            approver.add(dto.getSecondApprover());
            total++;
        }
        if (!StringUtils.isEmpty(dto.getThirdApprover())) {
            approver.add(dto.getThirdApprover());
            total++;
        }
        if (!StringUtils.isEmpty(dto.getFinalApprover())) {
            approver.add(dto.getFinalApprover());
            total++;
        }
        if (!StringUtils.isEmpty(dto.getFinalJudger())) {
            approver.add(dto.getFinalJudger());
            total++;
        }

    /*    if (approver.size() < total) {
            throw new AppBusinessException("五位考核人不能重复！");
        }*/
        if (StringUtils.isEmpty(dto.getDeptContactor())) {
            throw new AppBusinessException("部门接口人不能为空");
        }
        Date now = new Date();
        TbWorker dbWorker = getById(dto.getWorkerId());
        dto.setWorkerName(dbWorker.getWorkerName());
        Map<String, String> old_newWorkerIdMap = new HashMap<>();
        if (!StringUtils.isEmpty(dto.getFirstApprover())) {
            String s = dto.getFirstApprover();
            SdAllWorker firstApprover = commService.getAllWorkerDoFromLocalCache(s);
            if (!StringUtils.isEmpty(dbWorker.getFirstApprover())) {
                String s1 = dbWorker.getFirstApprover().split("/")[1];
                if (!s.equals(s1)) {
                    old_newWorkerIdMap.put(s1, s);
                }
            }
            dto.setFirstApprover(firstApprover.getWorkerName() + "/" + firstApprover.getWorkerId());
        }
        if (!StringUtils.isEmpty(dto.getSecondApprover())) {
//            SdAllWorker secApprover = (SdAllWorker)dataCacheMap.get("allworker-" + dto.getSecondApprover().split("/")[1]);
            SdAllWorker secApprover = commService.getAllWorkerDoFromLocalCache(dto.getSecondApprover());
            String s = dto.getSecondApprover();
            if (!StringUtils.isEmpty(dbWorker.getSecondApprover())) {
                String s1 = dbWorker.getSecondApprover().split("/")[1];
                if (!s.equals(s1)) {
                    old_newWorkerIdMap.put(s1, s);
                }
            }
            dto.setSecondApprover(secApprover.getWorkerName() + "/" + secApprover.getWorkerId());
        }
        if (!StringUtils.isEmpty(dto.getThirdApprover())) {
//            SdAllWorker thiApprover = (SdAllWorker)dataCacheMap.get("allworker-" + dto.getThirdApprover().split("/")[1]);
            SdAllWorker thiApprover = commService.getAllWorkerDoFromLocalCache(dto.getThirdApprover());
            String s = dto.getThirdApprover();
            if (!StringUtils.isEmpty(dbWorker.getThirdApprover())) {
                String s1 = dbWorker.getThirdApprover().split("/")[1];
                if (!s.equals(s1)) {
                    old_newWorkerIdMap.put(s1, s);
                }
            }
            dto.setThirdApprover(thiApprover.getWorkerName() + "/" + thiApprover.getWorkerId());
        }
        if (!StringUtils.isEmpty(dto.getFinalApprover()) && !dto.getFinalApprover().equals(dbWorker.getFinalApprover())) {
            SdAllWorker finApprover = commService.getAllWorkerDoFromLocalCache(dto.getFinalApprover());
            String s = dto.getFinalApprover();
            if (!StringUtils.isEmpty(dbWorker.getFinalApprover())) {
                String s1 = dbWorker.getFinalApprover().split("/")[1];
                if (!s.equals(s1)) {
                    old_newWorkerIdMap.put(s1, s);
                }
            }
            dto.setFinalApprover(finApprover.getWorkerName() + "/" + finApprover.getWorkerId());
        }
        if (!StringUtils.isEmpty(dto.getFinalJudger())) {
            SdAllWorker finJudger = commService.getAllWorkerDoFromLocalCache(dto.getFinalJudger());
            String s = dto.getFinalJudger();
            if (!StringUtils.isEmpty(dbWorker.getFinalJudger())) {
                String s1 = dbWorker.getFinalJudger().split("/")[1];
                if (!s.equals(s1)) {
                    old_newWorkerIdMap.put(s1, s);
                }
            }
            dto.setFinalJudger(finJudger.getWorkerName() + "/" + finJudger.getWorkerId());
        }

        if(!StringUtils.isEmpty(dto.getDirectManager())){
            if(!StringUtils.isEmpty(dbWorker.getDirectManager())){
                if(!dto.getDirectManager().equals(dbWorker.getDirectManager().split("/")[1])){
                    SdAllWorker dirManager = commService.getAllWorkerDoFromLocalCache(dto.getDirectManager());
                    dto.setDirectManager(dirManager.getWorkerName() + "/" + dirManager.getWorkerId());
                    dto.setChangeDeptManageFlag(TbWorker.changeFlag.YES.getCode());
                }else{
                    dto.setDirectManager(dbWorker.getDirectManager());
                }
            }else{
                SdAllWorker dirManager = commService.getAllWorkerDoFromLocalCache(dto.getDirectManager());
                dto.setDirectManager(dirManager.getWorkerName() + "/" + dirManager.getWorkerId());
                dto.setChangeDeptManageFlag(TbWorker.changeFlag.YES.getCode());
            }
        }
        if(!StringUtils.isEmpty(dto.getSecondManager())){
            if(!StringUtils.isEmpty(dbWorker.getSecondManager())){
                if(!dto.getSecondManager().equals(dbWorker.getSecondManager().split("/")[1])){
                    SdAllWorker secManager = commService.getAllWorkerDoFromLocalCache(dto.getSecondManager());
                    dto.setSecondManager(secManager.getWorkerName() + "/" + secManager.getWorkerId());
                    dto.setChangeSecManageFlag(TbWorker.changeFlag.YES.getCode());
                }else{
                    dto.setSecondManager(dbWorker.getSecondManager());
                }
            }else{
                SdAllWorker secManager = commService.getAllWorkerDoFromLocalCache(dto.getSecondManager());
                dto.setSecondManager(secManager.getWorkerName() + "/" + secManager.getWorkerId());
                dto.setChangeSecManageFlag(TbWorker.changeFlag.YES.getCode());
            }
        }
        if (!StringUtils.isEmpty(dto.getTeacherInfo())) {
            SdAllWorker teacher = commService.getAllWorkerDoFromLocalCache(dto.getTeacherInfo());
            dto.setTeacherInfo(teacher.getWorkerName() + "/" + teacher.getWorkerId());
            //导师指导时间记录
            if (dbWorker.getTeacherInfo() != null && dbWorker.getTeacherInfo().split("/")[1].equals(dto.getTeacherInfo())) {
                String dbTeacherId = dbWorker.getTeacherInfo().split("/")[1];
                teachScheduleMapper.updateByEndDate(dbWorker.getWorkerId(),new Date());
                TbTeachSchedule sc = new TbTeachSchedule();
                sc.setTeacherId(dbTeacherId);
                sc.setWorkerId(dbWorker.getWorkerId());
                sc.setStartDate(dbWorker.getTeacherInfo() == null ? dbWorker.getJoinDate(): new Date());
                teachScheduleMapper.insert(sc);
            }
        }
        if (!old_newWorkerIdMap.isEmpty()) {
            List<TbFlowInst> flow = tbFlowInstService.list(new QueryWrapper<TbFlowInst>()
                    .eq("worker_id", dbWorker.getWorkerId())
                    .in("approval_user_ids", old_newWorkerIdMap.keySet()));
            flow.forEach(i -> {
                LinkedList<TbFlowInstDTO> temp = new LinkedList<>();
                TbFlowInstDTO tbFlowInstDTO = new TbFlowInstDTO();
                BeanUtils.copyProperties(i, tbFlowInstDTO);
                tbFlowInstDTO.setApprovalUserIdsTransfer(old_newWorkerIdMap.get(i.getApprovalUserIds()));
                temp.add(tbFlowInstDTO);
                tbFlowInstService.transferSpecificFlowInst(temp);
            });
        }
        //获取思想导师工号
        String teacherInfo = dto.getTeacherInfo();
        if(!StringUtils.isEmpty(teacherInfo)){
            String str = teacherInfo.substring(0, teacherInfo.indexOf("/"));
            String workerId = teacherInfo.substring(str.length() + 1, teacherInfo.length());
            TbTeacher tbTeacher = teacherService.getOne(new QueryWrapper<TbTeacher>().eq("teacher_id", workerId));
            if (Objects.isNull(tbTeacher)){
                throw new AppBusinessException("您选择测思想导师不符合导师认证资质，请重新选择");
            }
            if (tbTeacher.getCertifiedStatus() != 3){
                throw new AppBusinessException("您所选的思想导师认证暂未通过，请重新选择!");
            }
        }

        //变更部门接口人
        dto.setDeptContactor(isChangeDeptCon(dbWorker,dto.getDeptContactor()));
        /*if (!dbWorker.getProbationMonth().equals(dto.getProbationMonth())) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DAY_OF_MONTH, -30);
            Date dbPassDate = dbWorker.getPassDate();
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
            int nowInt = Integer.parseInt(sf.format(now));
            int dbPassInt = Integer.parseInt(sf.format(dbPassDate));
            if (nowInt >= dbPassInt) {
                throw new AppBusinessException("该员工已经处于最后一个月的实习期，不能调整");
            }
            Calendar passInstance = Calendar.getInstance();
            passInstance.setTime(dbWorker.getJoinDate());
            passInstance.add(Calendar.MONTH, dto.getProbationMonth());
            dto.setPassDate(passInstance.getTime());
        }*/
        dto.setProbationMonth(null);
        dto.setPassDate(null);
        return tbWorkerMapper.updateTbWorker(JSONObject.parseObject(JSON.toJSONString(dto), TbWorker.class));
    }

    public String getSecondManager(String directManagerId){
        String token = "Bearer " + userUtils.getToken(inventoryAccount, inventoryPassword);
        SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyyMM");
        String[] managerArray = new String[]{directManagerId};
        JSONObject workerInfoJson = new JSONObject();
        workerInfoJson.put("empCode", managerArray);
        workerInfoJson.put("statDate", yyyy_MM.format(new Date()));
        String workerInfos = eosSyncDataClient.getWorkerInfo(token, workerInfoJson.toJSONString());
        Result<List<WorkerInfoClientDTO>> workerInfosResult = JSON.parseObject(workerInfos, new TypeReference<Result<List<WorkerInfoClientDTO>>>() {
        });
        if (workerInfosResult.getFlag() && workerInfosResult.getCode() == 20216) {
            WorkerInfoClientDTO man = workerInfosResult.getData().get(0);
            String directDirectManagerIds = man.getDirectManager();
            if (directDirectManagerIds == null) {
                SdAllWorker dirDirManager = commService.getAllWorkerDoFromLocalCache(directManagerId);
                return dirDirManager.getWorkerName() + "/" + dirDirManager.getWorkerId();
            } else {
                String[] directDirectManagerId = directDirectManagerIds.split(",");
                SdAllWorker dirDirManager = commService.getAllWorkerDoFromLocalCache(directDirectManagerId[0]);
                return dirDirManager.getWorkerName() + "/" + dirDirManager.getWorkerId();
            }
        } else {
            throw new AppBusinessException("获取隔级主管失败");
        }
    }

    public String isChangeDeptCon(TbWorker dbWorker,String deptContactor){
        //判断部门接口人 是否变更
        boolean changeDeptCon = false;
        String dbWorkerDeptContactor = dbWorker.getDeptContactor();
        if (deptContactor != null) {
            if (dbWorkerDeptContactor == null) {
                changeDeptCon = true;
            }else{
                String[] ids = deptContactor.split(",");
                for (String id : ids) {
                    if (!dbWorkerDeptContactor.contains(id)) {
                        changeDeptCon = true;
                        break;
                    }
                }
                if (!changeDeptCon) {
                    char[] chars = dbWorkerDeptContactor.toCharArray();
                    int count = 0;
                    for (char aChar : chars) {
                        if (aChar == ',') {
                            count++;
                        }
                    }
                    if (chars.length > 0 && ids.length != count + 1) {
                        changeDeptCon = true;
                    }
                }
            }
        }
        //部门接口人有变动 员工处于带启动考核环节 给新的接口人发送待办 删除不在了的接口人的待办
        if (changeDeptCon) {
            String[] cons = deptContactor.split(",");
            if (dbWorker.getWorkerStatus() == BusiEnumDefine.WORKER_STATUS_WAIT) {
                TodoTaskNodeEnum orderStatusEnum = TodoTaskNodeEnum.getEnumByValue(BusiEnumDefine.FLOW_STATUS_NEW_WORKRR_NOTICE);
                if (StringUtils.isEmpty(dbWorkerDeptContactor)) {
                    //新的接口人如果存在再原来的接口人字符串中 跳过 否则添加新的待办
                    initTodoTask(IdWorker.nextId() + "",
                            dbWorker.getWorkerId(),
                            deptContactor,
                            BusiEnumDefine.FLOW_NEW_WORKER_NOTICE,
                            dbWorker.getWorkerId() + "的" + orderStatusEnum.getName(),
                            orderStatusEnum.toString(),
                            BusiEnumDefine.FLOW_NEW_IN);

                } else {
//                    更换审批人
                    //旧的接口人中不存在 删除待办
                    StringBuilder account = new StringBuilder();
                    StringBuilder name = new StringBuilder();
                    for (String id : deptContactor.split(",")) {
                        SdAllWorker workerAccount = commService.getAllWorkerDoFromLocalCache(id);
                        account.append(workerAccount.getDomainAccount()).append(",");
                        name.append(workerAccount.getWorkerName()).append(",");
                    }
                    String ac = account.substring(0, account.length() - 1);
                    String na = name.substring(0, name.length() - 1);
                    String addUserAccount = commService.getAllWorkerDoFromLocalCache(dbWorker.getWorkerId()).getDomainAccount();
                    List<SdTodoTask> list = todoTaskService.list(new QueryWrapper<SdTodoTask>()
                            .eq("adduserid", addUserAccount)
                            .eq("processid", BusiEnumDefine.FLOW_NEW_WORKER_NOTICE));
                    list.forEach(i -> {
                        i.setAuthorid(ac);
                        i.setAuthorid(na);
                        todoTaskService.sendTodoTask(i);
                    });
                }
            }
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (String item : cons) {
                if (i != 0) {
                    sb.append(",");
                }
                SdAllWorker contactor = commService.getAllWorkerDoFromLocalCache(item);
                if (contactor != null) {
                    sb.append(contactor.getWorkerName()).append("/").append(contactor.getWorkerId());
                }
                i++;
            }
            return sb.toString();
        }else{
            return null;
        }
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(TbWorkerDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return tbWorkerMapper.deleteTbWorker(JSONObject.parseObject(JSON.toJSONString(dto), TbWorker.class));
        //return tbWorkerMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    @Override
    public void createCreateSpecificFlowInstS() {
        XxlJobLogger.log("定时任务创建流程");
        QueryWrapper<TbWorker> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("worker_status", 2);
        List<TbWorker> tbWorkers = tbWorkerMapper.selectList(queryWrapper);
        List<TbFlowInst> flowInstList = tbFlowInstService.list(new QueryWrapper<TbFlowInst>().lambda()
                .in(TbFlowInst::getWorkerId, tbWorkers.stream().map(TbWorker::getWorkerId).collect(Collectors.toList())));
        Set<String> flowWorkerIdCodeSet = flowInstList.stream().map(i -> i.getWorkerId() + i.getFlowCode() + i.getFlowName()).collect(Collectors.toSet());
        List<TbWorkerDTO> tbWorkerDTOS = JSONObject.parseArray(JSON.toJSONString(tbWorkers), TbWorkerDTO.class);
        XxlJobLogger.log("定时任务创建流程" + JSONObject.toJSONString(tbWorkerDTOS));
        tbWorkerDTOS.forEach(tbWorkerDTO -> {
            TransactionStatus status = null;
            try {
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);//新发起一个事务
                status = transactionManager.getTransaction(def);

                tbFlowInstService.createSpecificFlowInst(tbWorkerDTO,flowWorkerIdCodeSet);
                updateById(JSONObject.parseObject(JSON.toJSONString(tbWorkerDTO), TbWorker.class));
                XxlJobLogger.log("定时任务创建单个流程成功" + JSONObject.toJSONString(tbWorkerDTO));
                transactionManager.commit(status);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(tbWorkerDTO.getWorkerName() + "/" + tbWorkerDTO.getWorkerId() + "的创建流程失败， 异常信息为:" + e.getMessage());
                transactionManager.rollback(status);
            }
        });
    }

    public Map<String, Object> getWxWorkerData(GetFormBusinessData getFormBusinessData) {
        TbWorkerDTO workerDTO = new TbWorkerDTO();
        //flowId
        String docId = getFormBusinessData.getDocId();
        TbFlowInst tbFlowInst = tbFlowInstMapper.selectById(docId);
        //当前处理人
        String approvalUserIds = tbFlowInst.getApprovalUserIds();
        String workerId = tbFlowInst.getWorkerId();
        workerDTO.setWorkerId(workerId);
        //基本信息
        TbWorkerDTO basicInfo = getBasicInfo(workerDTO);
        String finalApprover = basicInfo.getFinalApprover().split("/")[0];
        StringBuilder deptSb = new StringBuilder();
        deptSb.append(basicInfo.getDept1name());
        if (!StringUtils.isEmpty(basicInfo.getDept2name())) {
            deptSb.append("/").append(basicInfo.getDept2name());
            if (!StringUtils.isEmpty(basicInfo.getDept3name())) {
                deptSb.append("/").append(basicInfo.getDept3name());
                if (!StringUtils.isEmpty(basicInfo.getDept4name())) {
                    deptSb.append("/").append(basicInfo.getDept4name());
                }
            }
        }
        basicInfo.setDeptFullName(deptSb.toString());
        basicInfo.setNameAndId(basicInfo.getWorkerName() + "/" + workerId);
        SdDept sdDept = sdDeptMapper.selectOne(new QueryWrapper<SdDept>().lambda().eq(SdDept::getDeptId, basicInfo.getDirectDeptId()));
        basicInfo.setWorkerType(sdDept.getDeptType());
        //ittp上岗屏蔽半导体
        if(sdDept.getDeptCodeChain().contains(noIttpRdDeptIds)){
            basicInfo.setWorkerType(sdDept.getDeptType()+"bdt");
        }

        //员工历史节点
        TbInstNodeDTO nodeDTO = getWorkerFlowNodes(workerDTO);
        Map<String, String> flowIdMap = new HashMap<>();
        Map<String, String> flowIdMapForFile = new HashMap<>();
        List<TbNodeDTO> nodeList = nodeDTO.getNodeList();
        nodeList.forEach(node -> {
            if (!StringUtils.isEmpty(node.getExamFlowId())) {
                flowIdMap.put(node.getExamFlowId(), node.getFillFlowId());
                flowIdMap.put(node.getFillFlowId(), node.getExamFlowId());
                flowIdMapForFile.put(node.getExamFlowId(), node.getFillFlowId());
            }
        });
        //员工承诺
        QueryWrapper<TbWorkerPromise> promiseWrapper = Wrappers.query();
        promiseWrapper.eq("worker_id", workerId)
                .eq("flow_id", flowIdMapForFile.getOrDefault(docId, docId))
                .orderByAsc("promise_order");
        List<TbWorkerPromise> workerPromises = tbWorkerPromiseMapper.selectList(promiseWrapper);
        //业务目标承诺
        List<TbWorkerPromise> busiTarget = new ArrayList<>();
        //个人发展承诺
        List<TbWorkerPromise> personalImprove = new ArrayList<>();
        workerPromises.forEach(promise -> {
            if (promise.getPromiseType().equals(BusiEnumDefine.PROMISE_BUSI_TARGET)) {
                busiTarget.add(promise);
            } else if (promise.getPromiseType().equals(BusiEnumDefine.PROMISE_PERSONAL_IMPROVE)) {
                personalImprove.add(promise);
            }
        });
        Map<String, Object> workerDataMap = new HashMap<>();
        StringBuilder approvalIdSb = new StringBuilder();
        if(!StringUtils.isEmpty(approvalUserIds)){
            for (String id : approvalUserIds.split(",")) {
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(id);
                if (workerDO != null) {
                    approvalIdSb.append(workerDO.getDomainAccount()).append(",");
                }
            }
        }
        StringBuilder approvalNames = new StringBuilder();
        if(!StringUtils.isEmpty(approvalUserIds)){
            for (String id : approvalUserIds.split(",")) {
                SdAllWorker workerDO = commService.getAllWorkerDoFromLocalCache(id);
                if (workerDO != null) {
                    approvalNames.append(workerDO.getWorkerName()).append(",");
                }
            }
        }

        String substring = "";
        if(!"".equals(approvalNames.toString())){
            substring = approvalNames.substring(0, approvalNames.toString().lastIndexOf(","));
        }

        List<HistoryInfo> historyInfos = tbFlowInstService.getHistoryInfos(docId);
//        if (flowIdMap.get(docId) != null) {
//            List<HistoryInfo> historyInfos1 = tbFlowInstService.getHistoryInfos(flowIdMap.get(docId));
//            if (historyInfos1.size() > 0) {
//                historyInfos.addAll(historyInfos1);
//            }
//        }
//        historyInfos.sort(Comparator.comparing(HistoryInfo::getApproveTime).reversed());
        //考核流程中获取填写流程里的文件
        List<Attachment> file = tbFlowInstService.getFileListByBusiId(BusiEnumDefine.PROMISE_ATTACHMENT, flowIdMapForFile.getOrDefault(docId, docId));
        workerDataMap.put("currentEmpNumber", approvalIdSb.toString());
        Map<String, Object> dataMap = new HashMap<>();
        JSONObject basicJson = JSONObject.parseObject(JSONObject.toJSONString(basicInfo, SerializerFeature.WriteMapNullValue));
        JSONObject nodeJson = JSONObject.parseObject(JSONObject.toJSONString(nodeDTO, SerializerFeature.WriteMapNullValue));
        dataMap.put("busiPromise", busiTarget);
        dataMap.put("personalPromise", personalImprove);
        dataMap.put("currentEmpNumber", substring);
        dataMap.put("finalApprover", finalApprover);

        dataMap.putAll(basicJson);
        dataMap.putAll(nodeJson);
        Object probationMonth = dataMap.get("probationMonth");
        if (probationMonth != null) {
            dataMap.put("probationMonth", ((Integer) probationMonth + "个月"));
        }
        if (file != null) {
            dataMap.put("file1", file);
        }
        workerDataMap.put("data", dataMap);
        workerDataMap.put("attachments", file);
        workerDataMap.put("historyInfos", historyInfos);
        return workerDataMap;
    }

    /**
     * 创建待办
     *
     * @param
     * @param nodeName
     * @param nodeId
     */
    private void initTodoTask(String flowId,
                              String sendWorkerId,
                              String approvalUserId,
                              String flowCode,
                              String nodeName,
                              String nodeId,
                              String processName) {
        SdTodoTask task = createTask(flowId, sendWorkerId, approvalUserId, flowCode, nodeName, nodeId, processName);
        todoTaskService.save(task);
        todoTaskService.sendTodoTask(task);
    }

    private SdTodoTask createTask(String flowId,
                                  String sendWorkerId,
                                  String approvalUserId,
                                  String flowCode,
                                  String nodeName,
                                  String nodeId,
                                  String processName){
        String workerDomainAccount;
        String workerName;
        if (!StringUtils.isEmpty(sendWorkerId)) {
            //通过当前处理人查出当前处理人AllWorker
            SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(sendWorkerId);
            workerDomainAccount = sdAllWorker.getDomainAccount();
            workerName = sdAllWorker.getWorkerName();
        } else {
            workerDomainAccount = "";
            workerName = "";
        }
        String accounts = "";
        String names = "";
        if (!StringUtils.isEmpty(approvalUserId)) {
            //通过当前处理人查出当前处理人AllWorker
            String[] authorIds = approvalUserId.split(",");
            for (int i = 0; i < authorIds.length; i++) {
                String authorId = authorIds[i];
                SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(authorId);
                if (sdAllWorker == null) {
                    sdAllWorker = allWorkerService.getById(authorId);
                }
                if (sdAllWorker == null) {
                    continue;
                }
                accounts = sdAllWorker.getDomainAccount();
                names = sdAllWorker.getWorkerName();
                if (i != authorIds.length - 1) {
                    accounts = accounts + ",";
                    names = names + ",";
                }
            }
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        SdTodoTask task = new SdTodoTask();
        task.setSystemid(systemId);
//        task.setSubject(BusiEnumDefine.FLOW_MONTH_FILL_NAME);
        task.setSubject(processName);
        task.setAccepttype(BusiEnumDefine.TODO_ACCEPT_PC);
        task.setAdduserid(workerDomainAccount);
        task.setAddusername(workerName);
        task.setAppid("nem-manage");
        task.setApplytime(sf.format(now));
        task.setAssigner("");
        task.setStatus(BusiEnumDefine.PERFORMANCE_TODO_APPROVING);
        task.setAuthorid(accounts);
        task.setAuthorname(names);
        StringBuilder url = new StringBuilder();
        url.append(todoPcUrl);
        String[] nodeIds = {"MONTH_WORK_PROMISE", "MONTH_PROMISE_APPROVAL", "MONTH_PROMISE_APPROVAL"};
        if (Arrays.asList(nodeIds).contains(nodeId)) {
            url.append("person/index/");
        }
        task.setUrl(url.toString());
        task.setTimestamp(sf.format(now));
        task.setMaildaily(null);
        task.setNodename(nodeName);
        task.setNodeid(nodeId);
        task.setProcessid(flowCode);
        task.setProcessname(processName);
        task.setRedirecturl("");
        //能否批量处理（1是\0否）
        task.setIsbatch("0");
        task.setDocunid(flowId);
        task.setEnduserid("");
        return task;
    }

    private SdTodoTask initTodoTask2(String flowId,
                              String sendAccount,
                              String sendName,
                              String approvalUserId,
                              String flowCode,
                              String nodeName,
                              String nodeId,
                              String processName) {
        String accounts = "";
        String names = "";
        if (!StringUtils.isEmpty(approvalUserId)) {
            //通过当前处理人查出当前处理人AllWorker
            String[] authorIds = approvalUserId.split(",");
            for (int i = 0; i < authorIds.length; i++) {
                String authorId = authorIds[i];
                SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(authorId);
                if (sdAllWorker == null) {
                    sdAllWorker = allWorkerService.getById(authorId);
                }
                if (sdAllWorker == null) {
                    continue;
                }
                accounts = sdAllWorker.getDomainAccount();
                names = sdAllWorker.getWorkerName();
                if (i != authorIds.length - 1) {
                    accounts = accounts + ",";
                    names = names + ",";
                }
            }
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        SdTodoTask task = new SdTodoTask();
        task.setSystemid(systemId);
//        task.setSubject(BusiEnumDefine.FLOW_MONTH_FILL_NAME);
        task.setSubject(processName);
        task.setAccepttype(BusiEnumDefine.TODO_ACCEPT_PC);
        task.setAdduserid(sendAccount);
        task.setAddusername(sendName);
        task.setAppid("nem-manage");
        task.setApplytime(sf.format(now));
        task.setAssigner("");
        task.setStatus(BusiEnumDefine.PERFORMANCE_TODO_APPROVING);
        task.setAuthorid(accounts);
        task.setAuthorname(names);
        StringBuilder url = new StringBuilder();
        url.append(todoPcUrl);
        String[] nodeIds = {"MONTH_WORK_PROMISE", "MONTH_PROMISE_APPROVAL", "MONTH_PROMISE_APPROVAL"};
        if (Arrays.asList(nodeIds).contains(nodeId)) {
            url.append("person/index/");
        }
        task.setUrl(url.toString());
        task.setTimestamp(sf.format(now));
        task.setMaildaily(null);
        task.setNodename(nodeName);
        task.setNodeid(nodeId);
        task.setProcessid(flowCode);
        task.setProcessname(processName);
        task.setRedirecturl("");
        //能否批量处理（1是\0否）
        task.setIsbatch("0");
        task.setDocunid(flowId);
        task.setEnduserid("");
        todoTaskService.save(task);
        return task;
    }

    @Override
    public List<TbWorkerDTO> selectHelpRecord(TbWorkerDTO dto) {
        List<TbWorker> tbWorkerList = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>().like("teacher_info", dto.getTeacherId()));
        return JSONArray.parseArray(JSONArray.toJSONString(tbWorkerList), TbWorkerDTO.class);
    }

    //新员工考核阶段相关人员离职维护邮件
    public void sendEmaiForUserResign(List<SdAllWorker> allWorkerList) {
        if (allWorkerList.isEmpty()) {
            return;
        }
        //待校验新员工
        List<TbWorker> tbWorkerListCheck = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>().in("worker_status", BusiEnumDefine.WORKER_STATUS_WAIT, BusiEnumDefine.WORKER_STATUS_CONDUCT));
        if (tbWorkerListCheck.isEmpty()) {
            return;
        }
        //所有离职员工Map,List
        Map<String, List<SdAllWorker>> allWorkerMap = allWorkerList.stream().collect(Collectors.groupingBy(SdAllWorker::getWorkerId));
        List<String> allWorkerList1 = allWorkerList.stream().map(SdAllWorker::getWorkerId).collect(Collectors.toList());

        //所有需要校验的相关人员
        List<String> workerList = tbWorkerListCheck.stream().map(TbWorker::getDirectManager).distinct().collect(Collectors.toList());
        List<String> teacherList = tbWorkerListCheck.stream().map(TbWorker::getTeacherInfo).distinct().collect(Collectors.toList());
        workerList.addAll(teacherList);
       /* List<String> secondManagerList = tbWorkerListCheck.stream().map(TbWorker::getSecondManager).distinct().collect(Collectors.toList());
        workerList.addAll(secondManagerList);*/
        List<String> firstApproverList = tbWorkerListCheck.stream().map(TbWorker::getFirstApprover).distinct().collect(Collectors.toList());
        workerList.addAll(firstApproverList);
        List<String> secondApproverList = tbWorkerListCheck.stream().map(TbWorker::getSecondManager).distinct().collect(Collectors.toList());
        workerList.addAll(secondApproverList);
        List<String> thirdApproverList = tbWorkerListCheck.stream().map(TbWorker::getThirdApprover).distinct().collect(Collectors.toList());
        workerList.addAll(thirdApproverList);
        List<String> finalApproverList = tbWorkerListCheck.stream().map(TbWorker::getFinalApprover).distinct().collect(Collectors.toList());
        workerList.addAll(finalApproverList);
        List<String> finalJudgerList = tbWorkerListCheck.stream().map(TbWorker::getFinalJudger).distinct().collect(Collectors.toList());
        workerList.addAll(finalJudgerList);

        //离职的相关人员
        List<String> resignWorkerList = new ArrayList<>();
        for (String s : workerList) {
            if (allWorkerList1.contains(s)) {
                resignWorkerList.add(s);
            }
        }
        if (resignWorkerList.isEmpty()) {
            return;
        }

        Map<String, Object> dataCacheMap = CommService.dataCacheMap;

        List<TbWorker> tbWorkerList = new ArrayList<>();

        for (String userInfo : resignWorkerList) {
            List<TbWorker> tbWorkers = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>().eq("direct_manager", userInfo)
                    .or().eq("teacher_info", userInfo)
                    .or().eq("first_approver", userInfo)
                    .or().eq("second_approver", userInfo)
                    .or().eq("third_approver", userInfo)
                    .or().eq("final_approver", userInfo)
                    .or().eq("finalJudger", userInfo));
            tbWorkerList.addAll(tbWorkers);
        }
        List<TbWorker> tbWorkerListChange = tbWorkerList.stream().distinct().collect(Collectors.toList());//涉及到相关人员变动的新员工
        Map<String, List<TbWorker>> tbWorkerMap = tbWorkerListChange.stream().collect(Collectors.groupingBy(TbWorker::getWorkerId));

        List<String> tbWorkerIdList = tbWorkerListChange.stream().map(TbWorker::getWorkerId).collect(Collectors.toList());
        List<SdAllWorker> sdAllWorkerList1 = sdAllWorkerMapper.selectList(new QueryWrapper<SdAllWorker>().in("worker_id", tbWorkerIdList));//涉及到人员变动的新员工的详细信息
        Map<String, List<SdAllWorker>> sdAllWorkerMap = allWorkerList.stream().collect(Collectors.groupingBy(SdAllWorker::getWorkerId));

        Map<String, List<TbWorker>> sendMap = new HashMap<>();
        List<String> sendIdList = new ArrayList<>();

        for (TbWorker tbWorker : tbWorkerListChange) {
            SdDept directDept = (SdDept) dataCacheMap.get("dept-" + tbWorker.getDirectDeptId());
            String bpUserId = directDept.getBpUserId();
            String contactorId = directDept.getContactorId();
            String gbbzId = directDept.getGbbzId();

            SdAllWorker newWorker = (SdAllWorker) dataCacheMap.get("allworker-" + tbWorker.getWorkerId());

            int jobLevel = Integer.parseInt(newWorker.getJobLevel());
            if (jobLevel >= 18) {
                for (String s : gbbzId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = sendMap.get(s);
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
            } else {
                for (String s : bpUserId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = sendMap.get(s);
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
                for (String s : contactorId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = sendMap.get(s);
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
            }
        }
        List<String> sendIdList1 = sendIdList.stream().distinct().collect(Collectors.toList());
        List<SdNoticeRecord> sendList = new ArrayList<>();
        SdEmailTemplate emailTemplate = emailTemplateService.getById(BusiEnumDefine.WORKER_USER_RESIGN);
        String content = emailTemplate.getEmailTemplateContent();
        if (!sendIdList1.isEmpty()) {
            for (String sendId : sendIdList1) {
                StringBuilder text = new StringBuilder();
                text.append("{");
                List<TbWorker> tbWorkerList1 = sendMap.get(sendId);
                for (TbWorker tbWorker : tbWorkerList1) {
                    text.append(tbWorker.getWorkerName()).append("/").append(tbWorker.getWorkerId());
                }
                text.append("}");

                SdAllWorker sendWorker = (SdAllWorker) dataCacheMap.get("allworker-" + sendId);
                if (sendWorker != null) {
                    SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
                    sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
                    sdNoticeRecord.setCopyToEmail("");
                    sdNoticeRecord.setTargetEmail(sendWorker.getEmail());
//                sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
                    sdNoticeRecord.setNoticeContent(content.replace("{姓名/工号}", text.toString()));
                    sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
                    sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                    sdNoticeRecord.setTargetName(sendWorker.getWorkerName());
                    sdNoticeRecord.setTargetId(sendWorker.getWorkerId());
                    sdNoticeRecord.setCreateTime(new Date());
                    sendList.add(sdNoticeRecord);
                }

            }
        }
        commService.sendMessage(sendList);
    }


    /**
     * @param allWorkerList //所有已离职员工
     */
    //新员工考核阶段离职邮件
    public void sendEmailForNewUserResign(List<SdAllWorker> allWorkerList) {
        if (allWorkerList.isEmpty()) {
            return;
        }
        //待校验新员工
        List<TbWorker> tbWorkerList = tbWorkerMapper.selectList(new QueryWrapper<TbWorker>().in("worker_status", BusiEnumDefine.WORKER_STATUS_WAIT, BusiEnumDefine.WORKER_STATUS_CONDUCT));
        if (tbWorkerList.isEmpty()) {
            return;
        }
        //所有离职员工Map,List
        Map<String, List<SdAllWorker>> allWorkerMap = allWorkerList.stream().collect(Collectors.groupingBy(SdAllWorker::getWorkerId));
        List<String> allWorkerList1 = allWorkerList.stream().map(SdAllWorker::getWorkerId).collect(Collectors.toList());
        //离职新员工
        List<TbWorker> tbWorkerResignList = new ArrayList<>();
        for (TbWorker tbWorker : tbWorkerList) {
            if (allWorkerList1.contains(tbWorker.getWorkerId())) {
                tbWorkerResignList.add(tbWorker);
            }
        }
        if (tbWorkerResignList.isEmpty()) {
            return;
        }

        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
//        Map<String,List<TbWorker>> tbWorkerGbbzMap=new HashMap<>();
//        Map<String,List<TbWorker>> tbWorkerBpUserMap=new HashMap<>();
//        Map<String,List<TbWorker>> tbWorkerContactorMap=new HashMap<>();
        Map<String, List<TbWorker>> sendMap = new HashMap<>();
//        List<String> gbbzIdList=new ArrayList<>();
//        List<String> bpUserIdList=new ArrayList<>();
//        List<String> contactorIdList=new ArrayList<>();
        List<String> sendIdList = new ArrayList<>();

        //离职新员工
        for (TbWorker tbWorker : tbWorkerResignList) {
            SdDept directDept = (SdDept) dataCacheMap.get("dept-" + tbWorker.getDirectDeptId());
            String bpUserId = directDept.getBpUserId();
            String contactorId = directDept.getContactorId();
            String gbbzId = directDept.getGbbzId();

            SdAllWorker newWorker = allWorkerMap.get(tbWorker.getWorkerId()).get(0);
            int jobLevel = Integer.parseInt(newWorker.getJobLevel());
            //职级
            if (jobLevel >= 18) {
                for (String s : gbbzId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = new ArrayList<>();
                    if (sendMap.get(s) != null) {
                        tbWorkers1.addAll(sendMap.get(s));
                    }
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
            } else {
                for (String s : bpUserId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = new ArrayList<>();
                    if (sendMap.get(s) != null) {
                        tbWorkers1.addAll(sendMap.get(s));
                    }
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
                for (String s : contactorId.split(",")) {
                    sendIdList.add(s);
                    List<TbWorker> tbWorkers1 = new ArrayList<>();
                    if (sendMap.get(s) != null) {
                        tbWorkers1.addAll(sendMap.get(s));
                    }
                    tbWorkers1.add(tbWorker);
                    sendMap.put(s, tbWorkers1);
                }
            }
        }
        List<String> sendIdList1 = sendIdList.stream().distinct().collect(Collectors.toList());
        List<SdNoticeRecord> sendList = new ArrayList<>();
        SdEmailTemplate emailTemplate = emailTemplateService.getById(BusiEnumDefine.NEW_WORKER_RESIGN);
        String content = emailTemplate.getEmailTemplateContent();
        if (!sendIdList1.isEmpty()) {
            for (String sendId : sendIdList1) {
                StringBuilder text = new StringBuilder();
                text.append("{");
                List<TbWorker> tbWorkerList1 = sendMap.get(sendId);
                for (TbWorker tbWorker : tbWorkerList1) {
                    text.append(tbWorker.getWorkerName()).append("/").append(tbWorker.getWorkerId());
                }
                text.append("}");

                SdAllWorker sendWorker = (SdAllWorker) dataCacheMap.get("allworker-" + sendId);
                if (sendWorker != null) {
                    SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
                    sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
                    sdNoticeRecord.setCopyToEmail("");
                    sdNoticeRecord.setTargetEmail(sendWorker.getEmail());
//                sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
                    sdNoticeRecord.setNoticeContent(content.replace("{姓名/工号}", text.toString()));
                    sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
                    sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                    sdNoticeRecord.setTargetName(sendWorker.getWorkerName());
                    sdNoticeRecord.setTargetId(sendWorker.getWorkerId());
                    sdNoticeRecord.setFlowId("-1");
                    sdNoticeRecord.setCreateTime(new Date());
                    sendList.add(sdNoticeRecord);
                }

            }
        }
        commService.sendMessage(sendList);
    }

    /**
     * 每天删除离职的导师
     *
     * */

    public void  deleteResignTeacher(List<SdAllWorker> allWorkerList){
        if (allWorkerList.isEmpty()) {
            return;
        }
        for (SdAllWorker sdAllWorker : allWorkerList) {
            TbTeacherDTO tbTeacherDTO = new TbTeacherDTO();
            tbTeacherDTO.setTeacherId(sdAllWorker.getWorkerId());
            teacherService.deleteDto(tbTeacherDTO);
        }
    }
    /**
     * 把offerWorker插入到tbWorker并发送代办和邮件
     * @param
     */
    public void insertOfferWorkerIntoWorker(TbOfferWorker offerWorker) {
        try {
            String workerId = offerWorker.getRegularWorkerId();
            TbWorker tbWorker = tbWorkerMapper.selectById(workerId);
            if (tbWorker == null) {
                generateAndSaveTbWorker(offerWorker, new TbWorker());
            } else {
                log.error("insertOfferWorkerIntoWorker时TbWorker已存在工号{}", workerId);
            }
        } catch (Exception e) {
            SdNoticeRecord notice = new SdNoticeRecord();
            SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m:s");
            notice.setNoticeId(IdWorker.nextId() + "");
            notice.setFlowId("-1");
            notice.setNoticeTitle("预备员工" + offerWorker.getWorkerId() + "/" + offerWorker.getWorkerName() + "入职后进新员工系统异常");
            notice.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            notice.setTargetEmail(inErrorMail);
            notice.setNoticeContent("域账号生成成功，因 " + e.getMessage() + " 异常导致员工进入新员工系统失败，请联系系统管理员解决<br>" + sdf.format(new Date()));
            asyncSendMessage.sendMessage(Collections.singletonList(notice));
            e.printStackTrace();
        }
    }

    public String formatDataSrc(String inType) {
        switch (inType) {
            case "应届毕业生(校招)":
                return "应届毕业生";
            case "应届毕业生(社招)":
            case "社会招聘":
                return "社会招聘";
            default:
                return "";
        }
    }

    public void generateAndSaveTbWorker(TbOfferWorker offerWorker, TbWorker worker) {
        worker.setWorkerId(offerWorker.getRegularWorkerId());
        String workerId = worker.getWorkerId();
        worker.setWorkerName(offerWorker.getWorkerName());
        worker.setDept1name(offerWorker.getDept1name());
        worker.setDept2name(offerWorker.getDept2name());
        worker.setDept3name(offerWorker.getDept3name());
        worker.setDept4name(offerWorker.getDept4name());
        if (StringUtils.isEmpty(offerWorker.getDirectDeptId())) {
            SdDept deptByNameChain = sdDeptService.getDeptByNameChain(offerWorker.getDeptNameChain());
            worker.setDirectDeptId(deptByNameChain.getDeptId());
        } else {
            worker.setDirectDeptId(Integer.parseInt(offerWorker.getDirectDeptId()));
        }
        //项目制部门新员工的不进tbWorker
        if (blockDept.contains(String.valueOf(worker.getDirectDeptId())) || offerWorker.getDeptNameChain().contains("代表处服务部/项目交付部")) {
            return;
        }
        worker.setJoinDate(offerWorker.getJoinDate());
        worker.setProbationMonth(offerWorker.getProbationMonth());
        worker.setPassDate(DateUtils.addMonths(offerWorker.getJoinDate(), offerWorker.getProbationMonth()));
        worker.setSex("男".equals(offerWorker.getSex()) ? 1 : 2);
        worker.setPostName(offerWorker.getPostName());
        worker.setWorkCity(offerWorker.getWorkCity());
        worker.setDataSrc(formatDataSrc(offerWorker.getInType()));
        worker.setCompanyName(offerWorker.getPersonnelRange());

        QueryWrapper<TbOfferStudy> studyWrapper = new QueryWrapper<>();
        studyWrapper.eq("worker_id", offerWorker.getWorkerId())
                .eq("is_highest_education", 1);
        List<TbOfferStudy> tbOfferStudies = tbOfferStudyMapper.selectList(studyWrapper);
        if (!CollectionUtils.isEmpty(tbOfferStudies)) {
            TbOfferStudy topEdu = tbOfferStudies.get(0);
            worker.setEduLevel(topEdu.getEducation().getTypeName());
            worker.setEduMajorName(topEdu.getMajorName());
        }

        worker.setAge(String.valueOf(com.h3c.nem.utils.DateUtil.getAge(offerWorker.getBirthday())));
        //todo 工作经历 没有
        String contactorId = sdDeptService.getContactorByDeptNameChain(offerWorker.getDeptNameChain(), offerWorker.getWorkCity());
        if (!org.apache.commons.lang3.StringUtils.isEmpty(contactorId)) {
            SdAllWorker allWorker = commService.getAllWorkerDoFromLocalCache(contactorId);
            worker.setDeptContactor(allWorker.getWorkerName() + "/" + contactorId);
        }
        worker.setTeacherInfo(offerWorker.getTeacherInfo());
        worker.setDirectManager(offerWorker.getDirectManager());

        String token = "Bearer " + userUtils.getToken(inventoryAccount, inventoryPassword);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String statDate = sdf.format(new Date());
        TbWorker workerForApi = new TbWorker();
        workerForApi.setDirectManager(!StringUtils.hasText(offerWorker.getDirectManager()) ? "" : offerWorker.getDirectManager());
        workerForApi.setDirectDeptId(worker.getDirectDeptId());
        workerForApi.setWorkerId(workerId);
        Map<String, String> manager = getManager(Collections.singletonList(workerForApi));
        Map<String, String> devGrade = getDevGrade(Collections.singletonList(workerId));
        JSONObject grade = psaClient.getGrade(Collections.singletonList(workerId));
        Map<String, Object> gradeMap = (Map<String, Object>) grade.get("data");

        if (gradeMap != null && gradeMap.get(workerId) != null) {
            worker.setNewExamScore(BigDecimal.valueOf((Double) gradeMap.get(workerId)).setScale(1, RoundingMode.HALF_UP));
        }
        if (devGrade.get(workerId) != null) {
            worker.setYanScore(Double.parseDouble(devGrade.get(workerId)));
        }
        //直接主管DTO 可获得他的上级主管工号

        worker.setSecondManager(manager.get(workerId));
        worker.setFirstApprover(worker.getTeacherInfo());
        worker.setFinalApprover(worker.getDirectManager());
        worker.setFinalJudger(worker.getSecondManager());
        worker.setCreateTime(new Date());
        worker.setWorkerStatus(BusiEnumDefine.WORKER_STATUS_WAIT);
        worker.setJobType(offerWorker.getJobGrade());
        worker.setJobLevel(offerWorker.getJobLevel());

        TodoTaskNodeEnum orderStatusEnum = TodoTaskNodeEnum.getEnumByValue(BusiEnumDefine.FLOW_STATUS_NEW_WORKRR_NOTICE);
        SdDept directDept = sdDeptService.getDeptByNameChain(offerWorker.getDeptNameChain());
        Set<String> sendBpDeptContectMap = new HashSet<>();
        List<SdTodoTask> tasks = new ArrayList<>();
        if (worker.getJobLevel() != null && Integer.parseInt(worker.getJobLevel()) >= 18) {
            sendBpDeptContectMap.add(directDept.getGbbzId());
            SdAllWorker gbbz = commService.getAllWorkerDoFromLocalCache(directDept.getGbbzId());
            if (gbbz != null) {
                SdTodoTask task = createTask(IdWorker.nextId() + "", worker.getWorkerId(), gbbz.getWorkerId(),
                        BusiEnumDefine.FLOW_NEW_WORKER_NOTICE, orderStatusEnum.getName(), orderStatusEnum.toString(),
                        BusiEnumDefine.FLOW_NEW_IN);
                tasks.add(task);
            }
        } else {
            String bpUserId = directDept.getBpUserId();
            if (!StringUtil.isEmpty(bpUserId)) {
                sendBpDeptContectMap.addAll(Arrays.asList(bpUserId.split(",")));
            }
            if (!StringUtil.isEmpty(contactorId)) {
                SdTodoTask task = createTask(IdWorker.nextId() + "",
                        worker.getWorkerId(),
                        contactorId,
                        BusiEnumDefine.FLOW_NEW_WORKER_NOTICE,
                        worker.getWorkerId() + "的" + orderStatusEnum.getName(),
                        orderStatusEnum.toString(),
                        BusiEnumDefine.FLOW_NEW_IN);
                tasks.add(task);
                sendBpDeptContectMap.addAll(Arrays.asList(contactorId.split(",")));
            }
        }
        tbWorkerMapper.insertTbWorker(worker);

        tasks.forEach(i -> {
            todoTaskService.sendTodoTask(i);
            todoTaskService.save(i);
        });

    }


    @Transactional
    public void syncWorkerByHrss() {
        String sapToken = commService.getSapToken(hrssUId, hrssPasswd);
        if (sapToken == null) {
            throw new AppBusinessException("获取hrsstoken失败");
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        JSONObject jo = new JSONObject();
        jo.put("startDate", sf.format(now));
        jo.put("endDate", sf.format(now));
        JSONObject workerRes = sapClient.empInfoOntime(jo.toJSONString(), sapToken);
        log.info(workerRes.toJSONString());
        boolean success = (boolean) workerRes.get("success");
        if (success) {
            List<TbWorker> dbList = list();
            Set<String> dbWorkerSet = dbList.stream().map(TbWorker::getWorkerId).collect(Collectors.toSet());
            Calendar calendar = Calendar.getInstance();
            String token = "Bearer " + userUtils.getToken(inventoryAccount, inventoryAccount);
            Map<String, Object> dataCacheMap = CommService.dataCacheMap;
            ArrayList hrssData = (ArrayList) workerRes.get("data");
            LinkedList<TbWorker> newWorkerList = new LinkedList<>();
            LinkedList<String> newWorkerIdList = new LinkedList<>();
            LinkedList<SdAllWorker> newAllWorkerList = new LinkedList<>();
            HashMap<String,String> workerAccountMap = new HashMap<>();
            if (hrssData == null) {
                log.info("hrss返回列表为空");
                return;
            }
            for (Object datum : hrssData) {
                NewHrssWorkerClientDTO clientDTO = JSONObject.parseObject(JSONObject.toJSONString(datum), NewHrssWorkerClientDTO.class);
                if (dbWorkerSet.contains(clientDTO.getWorkerId())) {
                    continue;
                }
                //9开头的外籍员工 跳过
                if (clientDTO.getWorkerId().startsWith("9")) {
                    continue;
                }

                //不存在对应部门 (项目制员工，不参加线上的新员工试用期管理2022/5/16 (周一) 10:18jzy邮件) 跳过
                SdDept dept = commService.getDept(Integer.parseInt(clientDTO.getDirectDeptId()));
                if (dept == null || clientDTO.getDirectDeptId().equals("50040000")){
                    continue;
                }

                if (dept.getDeptNameChain().contains("代表处服务部/项目交付部") || blockDept.contains(dept.getDeptId().toString())) {
                    continue;
                }
                TbWorker newWorker = new TbWorker();
                BeanUtils.copyProperties(clientDTO, newWorker);
                newWorker.setDirectDeptId(Integer.parseInt(clientDTO.getDirectDeptId()));
                String[] deptNameChain = dept.getDeptNameChain().split("/");
                int deptLength = deptNameChain.length;
                if (deptLength == 2) {
                    newWorker.setDept1name(deptNameChain[1]);
                    newWorker.setDept2name("");
                    newWorker.setDept3name("");
                    newWorker.setDept4name("");
                    newWorker.setDirectManager(dept.getDeptManagerId());
                } else if (deptLength == 3) {
                    newWorker.setDept1name(deptNameChain[1]);
                    newWorker.setDept2name(deptNameChain[2]);
                    newWorker.setDept3name("");
                    newWorker.setDept4name("");
                    newWorker.setDirectManager(dept.getDeptManagerId());
                } else if (deptLength == 4) {
                    newWorker.setDept1name(deptNameChain[1]);
                    newWorker.setDept2name(deptNameChain[2]);
                    newWorker.setDept3name(deptNameChain[3]);
                    newWorker.setDept4name("");
                    newWorker.setDirectManager(dept.getDeptManagerId());
                } else if (deptLength == 5) {
                    newWorker.setDept1name(deptNameChain[1]);
                    newWorker.setDept2name(deptNameChain[2]);
                    newWorker.setDept3name(deptNameChain[3]);
                    newWorker.setDept4name(deptNameChain[4]);
                    SdDept parDept = (SdDept) dataCacheMap.get("dept-" + dept.getParentId());
                    String deptManagerId = parDept.getDeptManagerId();
                    if (deptManagerId != null) {
                        newWorker.setDirectManager(deptManagerId.split(",")[0]);
                    }
                }
                newWorker.setDirectManager(commService.getAllWorkerDoFromLocalCache(newWorker.getDirectManager()).getWorkerName() + "/" + newWorker.getDirectManager());
                newWorker.setSex(clientDTO.getGender().equals("男") ? 1 : 2);
                newWorker.setCreateTime(now);
                newWorker.setJoinDate(now);
                newWorker.setProbationMonth(planProbationMonth);
                calendar.setTime(now);
                calendar.add(Calendar.MONTH, planProbationMonth);
                //默认转正时间默认时间+入职时间
                newWorker.setPassDate(calendar.getTime());
                newWorker.setWorkerStatus(BusiEnumDefine.WORKER_STATUS_WAIT);
                newWorkerList.add(newWorker);
                newWorkerIdList.add(newWorker.getWorkerId());
                workerAccountMap.put(clientDTO.getWorkerId(),clientDTO.getDomainAccount());
                SdAllWorker allWorker = new SdAllWorker();
                allWorker.setWorkerId(newWorker.getWorkerId());
                allWorker.setDomainAccount(clientDTO.getDomainAccount());
                allWorker.setEmail(clientDTO.getDomainAccount() + "@h3c.com");
                allWorker.setDirectDeptId(newWorker.getDirectDeptId());
                allWorker.setDept1id(Integer.parseInt(dept.getDeptCodeChain().split("/")[0]));
                allWorker.setSyncTime(now);
                allWorker.setWorkerName(newWorker.getWorkerName());

                newAllWorkerList.add(allWorker);
            }
            if (newWorkerList.isEmpty()) {
                return;
            }
            Map<String, String> empCodeMap = getEmpCodeMap(newWorkerIdList);
            //关联预备员工
            Map<String, TbPreWorker> preWorkerMap;
            if (empCodeMap.isEmpty()) {
                preWorkerMap = new HashMap<>();
            } else {
                List<TbPreWorker> preWorkerList = preWorkerService.list(new QueryWrapper<TbPreWorker>().in("pre_worker_id", empCodeMap.values()));
                //workerId->preWorker
                preWorkerMap = preWorkerList.stream().collect(Collectors.toMap(TbPreWorker::getPreWorkerId, i -> i));
            }
            /*Map<String, String> devGrade = getDevGrade(newWorkerIdList);
            JSONObject grade = psaClient.getGrade(newWorkerIdList);*/
            //成绩查询失败
        /*if (!(boolean)grade.get("success")) {
            log.error("同步失败：新员工成绩查询失败" + grade.get("message").toString());
            throw new AppBusinessException("新员工同步失败：新员工成绩查询失败");
        }*/
            //id->grade
            /*Map<String, Object> gradeMap = (Map<String, Object>) grade.get("data");*/
            List<SdTodoTask> tasks = new ArrayList<>();
            //给新员工加上成绩 关联预备员工
            newWorkerList.forEach(item -> {
                String preWorkerId = empCodeMap.get(item.getWorkerId());
                TbPreWorker preWorker = preWorkerMap.get(preWorkerId);
                if (preWorker != null) {
                    item.setTeacherInfo(preWorker.getTeacherInfo());
                    item.setDirectManager(preWorker.getDirectManager());
                    item.setProbationMonth(preWorker.getProbationMonth());
                    calendar.setTime(item.getJoinDate());
                    calendar.add(Calendar.MONTH, planProbationMonth);
                    item.setPassDate(calendar.getTime());
                }
                /*if (gradeMap != null) {
                    Object newExamScore = gradeMap.get(item.getWorkerId());
                    if (newExamScore != null) {
                        item.setNewExamScore(BigDecimal.valueOf((Double) newExamScore).setScale(1, BigDecimal.ROUND_HALF_UP));
                    }
                }
                String devG = devGrade.get(item.getWorkerId());
                item.setYanScore(devG == null ? null : Double.parseDouble(devG));*/
            });
            //获取主管map
            SimpleDateFormat yyyy_MM = new SimpleDateFormat("yyyyMM");
            Map<String, String> manager = getManager(newWorkerList);
            TodoTaskNodeEnum orderStatusEnum = TodoTaskNodeEnum.getEnumByValue(BusiEnumDefine.FLOW_STATUS_NEW_WORKRR_NOTICE);
            //格式存放的主管信息
            Set<String> sendBpDeptContectMap = new HashSet<>();
            for (TbWorker tbWorker : newWorkerList) {
                tbWorker.setSecondManager(manager.get(tbWorker.getWorkerId()));

                //第一考核人默认思想导师  最终考核人默认直接主管 最终评价人默认隔级主管
                tbWorker.setFirstApprover(tbWorker.getTeacherInfo());
                tbWorker.setFinalApprover(tbWorker.getDirectManager());
                // 三级主管及以下不到于总
                if (StringUtils.hasLength(tbWorker.getDept3name()) && tbWorker.getSecondManager().contains("68001")) {
                    tbWorker.setFinalJudger(tbWorker.getDirectManager());
                }else{
                    tbWorker.setFinalJudger(tbWorker.getSecondManager());
                }
                SdDept directDept = (SdDept) dataCacheMap.get("dept-" + tbWorker.getDirectDeptId());
                String contactors = null;
                String cityContactor = directDept.getCityContactor();
                boolean getCon = false;
                if (!StringUtils.isEmpty(cityContactor)) {
                    String[] cityContactors = cityContactor.split(";");
                    for (String contactorId : cityContactors) {
                        String[] city_ConId = contactorId.split(":");
                        if (city_ConId[0].equals(tbWorker.getWorkCity())) {
                            contactors = city_ConId[1];
                            getCon = true;
                        }
                    }
                }
                if (!getCon && !StringUtils.isEmpty(directDept.getContactorId())) {
                    contactors = directDept.getContactorId().split(",")[0];
                }
                if (!StringUtil.isEmpty(contactors)) {
                    String[] contactIds = contactors.split(",");
                    StringBuilder sb = new StringBuilder();
                    int i = 0;
                    for (String item : contactIds) {
                        if (i != 0) {
                            sb.append(",");
                        }
                        SdAllWorker contactor = (SdAllWorker) dataCacheMap.get("allworker-" + item);
                        sb.append(contactor.getWorkerName()).append("/").append(contactor.getWorkerId());
                        i++;

                    }
                    tbWorker.setDeptContactor(sb.toString());

                }
                String bpUserId = directDept.getBpUserId();
                String workerAccount = workerAccountMap.get(tbWorker.getWorkerId());
                if (Integer.parseInt(tbWorker.getJobLevel()) >= 18) {
                    sendBpDeptContectMap.add(directDept.getGbbzId());
                    SdAllWorker gbbz = (SdAllWorker) dataCacheMap.get("allworker-" + directDept.getGbbzId());
                    if (gbbz != null) {
                        SdTodoTask task = initTodoTask2(IdWorker.nextId() + "", workerAccount, tbWorker.getWorkerName(), gbbz.getWorkerId(),
                                BusiEnumDefine.FLOW_NEW_WORKER_NOTICE, orderStatusEnum.getName(), orderStatusEnum.toString(),
                                BusiEnumDefine.FLOW_NEW_IN);
                        tasks.add(task);
                    }
                } else {
                    if (!StringUtil.isEmpty(bpUserId)) {
                        sendBpDeptContectMap.addAll(Arrays.asList(bpUserId.split(",")));
                    }
                    if (!StringUtil.isEmpty(contactors)) {
                        SdTodoTask task = initTodoTask2(IdWorker.nextId() + "",
                                workerAccount,
                                tbWorker.getWorkerName(),
                                contactors,
                                BusiEnumDefine.FLOW_NEW_WORKER_NOTICE,
                                tbWorker.getWorkerId() + "的" + orderStatusEnum.getName(),
                                orderStatusEnum.toString(),
                                BusiEnumDefine.FLOW_NEW_IN);
                        tasks.add(task);
                        sendBpDeptContectMap.addAll(Arrays.asList(contactors.split(",")));
                    }
                }
            }
            saveBatch(newWorkerList);
            allWorkerService.saveBatch(newAllWorkerList);
            SdEmailTemplate emailTemplate = emailTemplateService.getById("NEW_WORKER_IN");
            List<SdNoticeRecord> sendList = new LinkedList<>();
            sendBpDeptContectMap.forEach(i -> {
                SdAllWorker BP = (SdAllWorker) dataCacheMap.get("allworker-" + i);
                if (BP != null) {
                    SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
                    sdNoticeRecord.setCopyToEmail("");
                    sdNoticeRecord.setTargetEmail(BP.getEmail());
                    sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
                    sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
                    sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
                    sdNoticeRecord.setTargetName(BP.getWorkerName());
                    sdNoticeRecord.setTargetId(BP.getWorkerId());
                    sdNoticeRecord.setCreateTime(new Date());
                    sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
                    sdNoticeRecord.setFlowId("BPNOTICE");
                    sendList.add(sdNoticeRecord);
                }
            });
            commService.sendMessage(sendList);
            tasks.forEach(i -> {
                todoTaskService.sendTodoTask(i);
            });
        } else {
            log.error(workerRes.get("message").toString());
            throw new AppBusinessException("获取新入职员工失败");
        }
    }


    /**
     * 获取卡证制卡人员信息
     *
     * @Param: dto 实体查询参数信息
     * @Author: h24002
     * @Date: 2022/6/24
     */
    @Override
    public List<TbWorkerCardDTO> getWorkerCardListByDto(TbWorkerCardQueryDTO dto) {
        List<TbWorkerCardDTO> dtoList = tbWorkerMapper.getWorkerCardList(dto);
        for (TbWorkerCardDTO cardDTO : dtoList) {
            EducationLevelEnum education = cardDTO.getEducation();
            if (education != null && StringUtils.hasText(education.getTypeName())) {
                cardDTO.setEducationName(education.getTypeName());
            }
        }
        return dtoList;
    }

    /**
     * 导出卡证制卡人员信息--Excel导出
     *
     * @Param: dto 查询参数（无分页）
     * @Param: templateCode 模板编码
     * @Param: downLoadFileName 要下载的文件名称
     * @Author: h24002
     * @Date: 2022/6/27
     */
    @Override
    public File exportWorkerCardListByDto(TbWorkerCardQueryDTO dto, String templateCode, String downLoadFileName) {
        List<TbWorkerCardDTO> dtoList = tbWorkerMapper.getWorkerCardList(dto);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (TbWorkerCardDTO cardDTO : dtoList) {
            EducationLevelEnum education = cardDTO.getEducation();
            if (education != null && StringUtils.hasText(education.getTypeName())) {
                cardDTO.setEducationName(education.getTypeName());
            }
            if(cardDTO.getJoinDate() != null){
                cardDTO.setJoinDateStr(sdf.format(cardDTO.getJoinDate()));
            }
        }
        return commService.generateExportFile(downLoadFileName, templateCode, (List) dtoList);
    }


    /**
     * 获取工卡照片人员信息
     *
     * @Param: dto 实体查询参数信息
     * @Author: h24002
     * @Date: 2022/6/24
     */
    @Override
    public List<TbWorkerCardImageDTO> getWorkerCardImageListByDto(TbWorkerCardQueryDTO dto) {
        List<TbWorkerCardImageDTO> dtoList = tbWorkerMapper.getWorkerCardImageList(dto);
        return dtoList;
    }

    /**
     * 导出人员工卡照片压缩包
     *
     * @Param: imgList 要导出的员工信息（需包含链接，sfs文件ID）
     * @Param: dto 实体查询参数信息
     * @Author: h24002
     * @Date: 2022/6/24
     */
    @Override
    public Map<String, Object> exportWorkerCardImageArrayByDto(List<TbWorkerCardImageDTO> imgList, TbWorkerCardQueryDTO dto) {
        //若没提供勾选的导出名单，则从系统中进行查询
        if (imgList == null || imgList.stream().count() == 0) {
            imgList = tbWorkerMapper.getWorkerCardImageList(dto);
        }
        if (imgList.size() > 0) {
            File tempDir = new File("download/WorkerCards/DownLoadImg/");
            if (!tempDir.exists() || !tempDir.isDirectory()) {
                tempDir.mkdirs();
            }
            String basePath = tempDir.getPath();
            String[] content = tempDir.list();//取得当前目录下所有文件和文件夹
            for (String name : content) {
                File temp = new File(basePath, name);
                temp.delete();
            }

            List<String> errMsgList = new ArrayList();
            List<File> okList = new ArrayList();
            for (TbWorkerCardImageDTO item : imgList) {
                String workerCode = item.getWorkerCode();
                String imgUrl = item.getFilePath();
                String imgId = item.getFileId();
                String imgName = item.getFileName();
                if (!StringUtils.hasText(workerCode)) {
                    errMsgList.add(String.format("员工%s还未生成正式工号", item.getWorkerId()));
                    continue;
                }

                // 要么是旧的链接
                if (StringUtils.hasText(imgUrl)) {
                    try {
                        //筛选出文件名称
                        String fileName = imgUrl.lastIndexOf("/") > 0 ? imgUrl.substring(imgUrl.lastIndexOf("/") + 1) : "";
                        //拿到文件后缀
                        String extension = fileName.lastIndexOf(".") > 0 ? fileName.substring(fileName.lastIndexOf(".")) : ".jpg";
                        //工号类的文件名
                        String newFileName = CommonUtil.GetEmpCodeTo5(workerCode) + extension;
                        //保存的文件路径，含文件名
                        String filePath = basePath + File.separator + newFileName;
                        File imgFile = new File(filePath);
                        //是否之前已经生成了，若是生成了则直接拿到地址，否则下载文件到本地
                        if (imgFile == null || !imgFile.exists()) {
                            String url = "http://hrss-rzdj.h3c.com" + imgUrl;
                            File saveFile = downLoadFromUrl(url, newFileName, basePath);
                            if (saveFile == null) {
                                errMsgList.add(String.format("员工%s远程抓取照片失败", workerCode));
                                continue;
                            } else {
                                okList.add(saveFile);
                            }
                        } else {
                            okList.add(imgFile);
                        }
                    } catch (Exception ex) {
                        errMsgList.add(String.format("员工%s远程抓取照片异常：%s", workerCode, ex.getMessage()));
                        continue;
                    }
                }
                //要么是sfs文件ID
                else if (StringUtils.hasText(imgId)) {
                    try {
                        //拿到文件后缀
                        String extension = imgName.lastIndexOf(".") > 0 ? imgName.substring(imgName.lastIndexOf(".")) : ".jpg";
                        //工号类的文件名
                        String newFileName = CommonUtil.GetEmpCodeTo5(workerCode) + extension;
                        File file = commService.getFile(imgId, newFileName);
                        if (file == null) {
                            errMsgList.add(String.format("员工%s远程抓取照片失败", workerCode));
                            continue;
                        } else {
                            okList.add(file);
                        }
                    } catch (IOException ex) {
                        errMsgList.add(String.format("员工%s远程抓取照片异常：%s", workerCode, ex.getMessage()));
                        continue;
                    }
                } else {
                    errMsgList.add(String.format("员工 %s 未上传照片", workerCode));
                }
            }

            String errMsg = errMsgList.size() > 0 ?
                    String.format("存在异常数据:【%s】", String.join("；", errMsgList)) : "";
            String okMsg = String.format("共检索出 %s 人工卡照片，正在下载，请稍后。%s", okList.size(), errMsg);

            String timeStr = com.eos.common.util.DateUtils.dateFormat(new Date(), "yyyyMMddHHmmss");
            String zipName = "工卡照片导出" + timeStr + ".zip";
            String zipPath = basePath + File.separator + zipName;
            File zipFile = new File(zipPath);
            if (!CollectionUtils.isEmpty(okList)) {
                CommonUtil.zipFiles(okList, zipFile);

                Map<String, Object> fileResult = new HashMap<>();
                fileResult.put("msg", okMsg);
                fileResult.put("file", zipFile);

                return fileResult;
            } else {
                throw new AppBusinessException("下载ZIP文件失败：" + errMsg);
            }
        } else {
            throw new AppBusinessException("导出工卡照片失败：未找到合适的数据");
        }
    }

    @Override
    public void sendRegularWorkerToContact() {

        Calendar nowCalendar = Calendar.getInstance();
        int nowDay = nowCalendar.get(Calendar.DAY_OF_MONTH);
        nowCalendar.set(Calendar.HOUR_OF_DAY, 0);
        nowCalendar.set(Calendar.MINUTE, 0);
        nowCalendar.set(Calendar.SECOND, 0);
        nowCalendar.set(Calendar.MILLISECOND, 0);
        List<TbWorker> list;
        if (nowDay == 1) {
            //一号 发送下半月
            nowCalendar.set(Calendar.DAY_OF_MONTH, 16);
            Date startTime = nowCalendar.getTime();
            nowCalendar.set(Calendar.DAY_OF_MONTH, nowCalendar.getMaximum(Calendar.DAY_OF_MONTH));
            Date endTime = nowCalendar.getTime();
            list = list(new QueryWrapper<TbWorker>().lambda().between(TbWorker::getPassDate, startTime, endTime));
        } else {
            //十五号发送下个月上半月
            //一号 发送下半月
            nowCalendar.add(Calendar.MONTH, 1);
            nowCalendar.set(Calendar.DAY_OF_MONTH, 1);
            Date startTime = nowCalendar.getTime();
            nowCalendar.set(Calendar.DAY_OF_MONTH, 15);
            Date endTime = nowCalendar.getTime();
            list = list(new QueryWrapper<TbWorker>().lambda().between(TbWorker::getPassDate, startTime, endTime));
        }
//        PASS_LIST
        //查出所有待发送的接口人和转正名单
        Map<String, List<RegularWorkerDTO>> resMap = new HashMap<>();
        list.forEach(item -> {
            RegularWorkerDTO regularWorker = new RegularWorkerDTO();
            BeanUtils.copyProperties(item, regularWorker);
            regularWorker.setDirectManagerName(item.getDirectManager());
            SdDept dept = commService.getDept(item.getDirectDeptId());
            regularWorker.setBP(dept.getBpUserName() + "/" + dept.getBpUserId());
            String[] contacts = item.getDirectManager().split(",");
            for (String contact : contacts) {
                List<RegularWorkerDTO> regularWorkerDTOS = resMap.get(contact);
                if (regularWorkerDTOS == null) {
                    ArrayList<RegularWorkerDTO> tempList = new ArrayList<>();
                    tempList.add(regularWorker);
                    resMap.put(item.getDeptContactor(), tempList);
                } else {
                    regularWorkerDTOS.add(regularWorker);
                }
            }
        });

        SdEmailTemplate emailTemplate = emailTemplateService.getById("SEND_REGULAR");
//        String loginUserId = commService.getLoginUserId();
        resMap.forEach((key, value) -> {
            List<File> files = new ArrayList<>(1);
            File file = commService.generateExportFile("转正名单", "PASS_LIST", (List) value);
            files.add(file);
            String[] targetNameId = key.split("/");
            SdAllWorker targetWorker = commService.getAllWorkerDoFromLocalCache(targetNameId[1]);
            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId(IdWorker.nextId() + "");
            sdNoticeRecord.setApplyUserId("-1");
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            sdNoticeRecord.setTargetId(targetNameId[1]);
            sdNoticeRecord.setTargetName(targetNameId[0]);
            sdNoticeRecord.setTargetEmail(targetWorker.getEmail());
            sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
            sdNoticeRecord.setNoticeContent(emailTemplate.getEmailTemplateContent());
            sdNoticeRecord.setCreateTime(new Date());
            sdNoticeRecord.setCopyToEmail("");
            asyncSendMessage.sendMessage(sdNoticeRecord, files);
        });
    }

    @Override
    public void finishDeclare(List<Integer> workerIds) {
        List<TbTeachSchedule> teachSchedules = teachScheduleMapper.selectList(new QueryWrapper<TbTeachSchedule>()
                .lambda().eq(TbTeachSchedule::getTeachSecId, workerIds));
        Date now = new Date();
        for (Integer workerId : workerIds) {
            TbTeachSchedule tbTeachSchedule = new TbTeachSchedule();
            tbTeachSchedule.setTeachSecId(workerId);
            tbTeachSchedule.setAllowanceFlag(1);
            tbTeachSchedule.setAllowanceDate(now);
            teachScheduleMapper.updateById(tbTeachSchedule);
        }

        Set<String> collect = teachSchedules.stream().map(TbTeachSchedule::getTeacherId).collect(Collectors.toSet());
        SdEmailTemplate template = emailTemplateService.getById("teach_allowance");

        collect.forEach(item -> {
            SdAllWorker teacher = commService.getAllWorkerDoFromLocalCache(item);
            Set<TbTeachSchedule> collect1 = teachSchedules.stream().filter(i -> i.getTeacherId().equals(item)).collect(Collectors.toSet());
            StringBuilder stus = new StringBuilder();
            for (TbTeachSchedule schedule : collect1) {
                SdAllWorker stu = commService.getAllWorkerDoFromLocalCache(schedule.getWorkerId());
                stus.append(",").append(stu.getWorkerName());
            }
            String content = template.getEmailTemplateContent().replace("{{teacherName}}", teacher.getWorkerName())
                    .replace("{{workerName}}", stus.toString());
            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
            sdNoticeRecord.setFlowId(IdWorker.nextId() + "");
            sdNoticeRecord.setApplyUserId("-1");
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            sdNoticeRecord.setTargetId(teacher.getWorkerId());
            sdNoticeRecord.setTargetName(teacher.getWorkerName());
            sdNoticeRecord.setTargetEmail(teacher.getEmail());
            sdNoticeRecord.setNoticeTitle(template.getEmailTemplateTitle());
            sdNoticeRecord.setNoticeContent(content);
            sdNoticeRecord.setCreateTime(now);
            sdNoticeRecord.setCopyToEmail("");
            asyncSendMessage.sendMessage(sdNoticeRecord,null);
        });
    }

    @Override
    public void checkFinishWorker() {
        baseMapper.updateFinishWorker();
        baseMapper.updateFinishWorkerCan();
        baseMapper.updateFinishWorkerNot();
    }

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr   url地址
     * @param fileName 文件名
     * @param savePath 保存路径
     * @Author: h24002
     * @Date: 2022/6/24
     */
    public static File downLoadFromUrl(String urlStr, String fileName, String savePath) {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);
            if (getData.length <= 0) {
                throw new Exception("未找到文件");
            }
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }

            log.info("info:" + urlStr + " download success");
            return file;
        } catch (Exception e) {
            log.error("info:" + urlStr + " download failed:" + e.getMessage());
            return null;
        }
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream 输入的文件流
     * @Author: h24002
     * @Date: 2022/6/24
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    /**
     * 新员工的接口人接口人离职通知管理员
     * */
    @Override
    public void sendMailForContactorResign(){
        List<TbWorkerDTO> tbWorkerList = tbWorkerMapper.queryListForContactorResign();
        List<String> workerIdList = tbWorkerList.stream().map(TbWorkerDTO::getWorkerId).collect(Collectors.toList());
        SdAllWorker manager =commService.getWorkerIdByDomain(adminDomainAccounts.split(",")[0]);
        SdEmailTemplate template = emailTemplateService.getById("contactResign");
        String templateTitle = template.getEmailTemplateTitle();
        String templateContent = template.getEmailTemplateContent();
        SdNoticeRecord emailRecord = new SdNoticeRecord();
        emailRecord.setApplyUserId("-1");
        emailRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
        emailRecord.setTargetId(manager.getWorkerId());
        emailRecord.setTargetName(manager.getWorkerName());
        emailRecord.setTargetEmail("jin.zhiyuan@h3c.com");
        emailRecord.setNoticeTitle(templateTitle);
        templateContent = templateContent.replace("{员工}",CommonUtil.contactListStrings(workerIdList));
        emailRecord.setNoticeContent(templateContent);
        emailRecord.setCreateTime(new Date());
        emailRecord.setNoticeId(IdWorker.nextId() + "");
        commService.sendMessage(emailRecord);
    }
}
